简体   繁体   English

JS“点击”事件侦听器<select>需要点击两次吗?

[英]JS 'click' Event Listener on <select> is taking two clicks?

I have a simple filter set on a select tag with three options.我在带有三个选项的 select 标签上设置了一个简单的过滤器。 When i change to a new option the list should filter.当我更改为新选项时,列表应进行过滤。 This works but i have to select one of the three options and then click the select box again for it to take effect?这有效,但我必须选择三个选项之一,然后再次单击选择框才能生效? Is there an obvious reason for this?这有明显的原因吗?

HTML HTML

            <select name = "todos" class = "filter-todo">
                <option value = "all">All</option>
                <option value = "completed">Completed</option>
                <option value = "uncompleted">Uncompleted</option>
            </select>
        </div>

JS JS

const filterTodo = (e) => {                                 //needs fixing(the options need two clicks)
    const todos = todoList.childNodes
    todos.forEach(function(todo){
        switch(e.target.value){
            case "all":
                todo.style.display = "flex"
                break;
            case "completed":
                if (todo.classList.contains('completed')){
                    todo.style.display = "flex"
                } else {
                    todo.style.display = "none"
                }
                break;
            case "uncompleted":
                if (!todo.classList.contains('completed')){
                    todo.style.display = "flex"
                } else 
                    todo.style.display = "none"
                break;
        }
    })
} 

const filterOption = document.querySelector('.filter-todo')
filterOption.addEventListener('click', filterTodo)

click is the wrong event to subscribe to. click是错误的订阅事件。 It will fire upon any click inside of the DOM tree, including on the option s themselves.它会在 DOM 树内的任何点击时触发,包括option本身。 To avoid this select has another event you should subscribe to instead.为了避免这个select有另一个你应该订阅的事件。 Just change one line and you're good to go:只需更改一行即可:

filterOption.addEventListener('change', filterTodo)

This fires when the value changes, so when it's selected option is updated.这会在值更改时触发,因此当它被选中时选项会更新。 More information can be found in plenty of places, so for good measure here is MDN on it .更多的信息可以在很多地方找到,所以这里是 MDN 上的一个很好的衡量标准。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM