防止在 window 滚动时更改 var 值(选定的选项)

Prevent var value (selected option) changes on window scroll

获取 selected 选项值并将其传递给函数。但是,请注意 window 滚动值更改和 return 所有以前 selected 值。

请参阅 codepen 处的代码 检查控制台。

重现问题

  1. 在下拉菜单中,select 2018 并滚动。在控制台中,如预期的行为 returns
"change: 2018"
"init: 2018"
"scroll: 2018"
  1. 清除控制台。更改为 2019 并滚动。在控制台中,return 是一个“2018”“2019”的循环。预期行为仅限“2019”。
"change: 2019"
"init: 2019"
"scroll: 2018"
"scroll: 2019"
"scroll: 2018"
"scroll: 2019"
(function () {
  document.addEventListener('DOMContentLoaded', function () {
    var select = document.querySelector('select')

    // Register click event listener for select element
    select.addEventListener('change', handleLibsynSelectChange, true)

    // Handle select change
    function handleLibsynSelectChange(e) {
      var year = e.target.value
      console.log('change: ' + year)
      handleLibsynInit(year)
    }

    function handleLibsynInit(libsynFilterYear) {
      console.log('init: ' + libsynFilterYear)
      window.addEventListener('scroll', function() {
        console.log('scroll: ' + libsynFilterYear)
        // other functions to execute on window scroll which need the var libsynFilterYear
      })
    }
  })
})()

关于这条评论:

如何将所选值从更改处理程序传递到滚动处理程序?

只需在 'change' 事件侦听器中获取选定的值。

(function () {
  document.addEventListener('DOMContentLoaded', function () {
    var select = document.querySelector('select');
    var yearSelected = -1;
    // Register click event listener for select element
    select.addEventListener('change', handleLibsynSelectChange, true);
    // Handle select change
    function handleLibsynSelectChange(e) {
      yearSelected = e.target.value
    };
    var listener = function () {
      console.dir('scroll : ' + yearSelected);
    };
    window.addEventListener('scroll',listener);
  });
})()