使用按钮滚动下拉列表

Using buttons to scroll dropdown

我想使用 'up' 和 'down' 按钮滚动选项。最终,实际的下拉列表将对用户隐藏。这个例子我让它可见。我不能在 button 标签中使用 onclick,因为这将是一个 Chrome 扩展。问题是按钮似乎没有任何作用。

document.addEventListener('DOMContentLoaded', function() {  
    document.getElementById('d').addEventListener('click', theme(this));
    document.getElementById('u').addEventListener('click', theme(this));
});
var ddl = document.getElementById("s")
function theme(x) {
  if (x.value === 'down') {
    ddl.selectedIndex = ddl.selectedIndex + 1
  } else {
    ddl.selectedIndex = ddl.selectedIndex - 1
  }
};
<select id="s">
    <option>Dog</option>
    <option>Cat</option>
    <option>Bird</option>
    <option>Lizard</option>
    <option>Snake</option>   
</select>
    <button id="d" type="button" value="up">up</button>
    <button id="u" type="button" value="down">down</button>
    <script src="test.js"></script>

这个位有 2 个问题 addEventListener('click', theme(this));。你认为当你点击按钮时它会调用 theme(this)this 将是你点击的按钮。但首先,this 在此上下文中是 window 而不是按钮,其次,theme(this) 在执行 addEventListener 时立即被调用,因为它没有 return 任何你不附加任何事件监听器的东西。试试这个:

document.addEventListener('DOMContentLoaded', function() {
    document.getElementById('d').addEventListener('click', () => theme('up'));
    document.getElementById('u').addEventListener('click',() => theme('down'));
});
var ddl = document.getElementById("s")
function theme(x) {
  if (x === 'down') {
    ddl.selectedIndex = ddl.selectedIndex + 1
  } else if(ddl.selectedIndex > 0){
      ddl.selectedIndex = ddl.selectedIndex - 1
  }
};
<select id="s">
    <option>Dog</option>
    <option>Cat</option>
    <option>Bird</option>
    <option>Lizard</option>
    <option>Snake</option>   
</select>
    <button id="d" type="button" value="up">up</button>
    <button id="u" type="button" value="down">down</button>
    <script src="test.js"></script>