css 从HTML中检索data* 值并使用Javascript将其打印到控制台中

yhqotfr8  于 2023-01-27  发布在  Java
关注(0)|答案(1)|浏览(123)

我不知道这段代码做错了什么,我上网查了一下,我所看到的就是把window.onload = function()放在代码的开头,但是,这个值总是打印为null,我不知道为什么它会这样做。
下面是代码:

window.onload = function () {
    // Get the select element by its id
    const select = document.getElementById("select-filter");

    // Get the selected option element
    const selectedOption = select.options[select.selectedIndex];

    // Get the data-select value
    const dataSelect = selectedOption.getAttribute("data-sel");

    // Print the data-select value to the console
    console.log(dataSelect);
}
<div class="filter-select-container">
  <!-- filter selector -->
  <div class="filter-selection-container">
    <select name="select-filter" id="select-filter">
      <option value="filter-all">All</option>
      <option value="filter-commercials" data-sel="1">Commercials</option>
      <option value="filter-fiction" data-sel="2">Fiction</option>
      <option value="filter-music-videos" data-sel="3">Music Videos</option>
    </select>
  </div>
</div>

感谢您的帮助:)

w46czmvw

w46czmvw1#

您可能希望select上有一个change listener,然后在尝试记录它之前检查是否定义了data属性。

const select = document.getElementById("select-filter");

select.addEventListener('change', handleChange);

function handleChange() {
  const selectedOption = select.options[select.selectedIndex];
  const dataSelect = selectedOption.getAttribute("data-sel");
  if (dataSelect) console.log(dataSelect);
}
<div class="filter-select-container">
  <!-- filter selector -->
  <div class="filter-selection-container">
    <select name="select-filter" id="select-filter">
      <option value="filter-all">All</option>
      <option value="filter-commercials" data-sel="1">Commercials</option>
      <option value="filter-fiction" data-sel="2">Fiction</option>
      <option value="filter-music-videos" data-sel="3">Music Videos</option>
    </select>
  </div>
</div>

相关问题