使用JavaScript从我的HTML中检索数据值并将其打印到控制台
P粉381463780
P粉381463780 2024-03-31 13:31:58
0
1
408

我不知道这段代码做错了什么,我在网上查了一下,我所看到的就是将 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>

感谢您的帮助:)

P粉381463780
P粉381463780

全部回复(1)
P粉682987577

您可能意味着 select 有一个 change 侦听器 ,然后在尝试记录之前检查数据属性是否已定义。

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);
}
热门教程
更多>
最新下载
更多>
网站特效
网站源码
网站素材
前端模板
关于我们 免责声明 Sitemap
PHP中文网:公益在线PHP培训,帮助PHP学习者快速成长!