简体   繁体   English

如果单击 select 菜单中的第一个元素,如何让事件侦听器不被忽略

[英]how to get event listener not to ignore if the first element in the select menu is clicked

i have tried the traditional method of addEventListener change but if i click on the first element on the list it wont respond, it only works if i click on australia then india...我已经尝试过改变addEventListener 的传统方法,但是如果我点击列表中的第一个元素它不会响应,它只有在我点击澳大利亚然后印度时才有效......

HTML HTML

<select id="country" >
 <option value="india">India</option>
 <option value="australia">Australia</option>
 <option value="turkey">Turkey</option>
</select> 

JS JS

var a = document.getElementById('country');
a.addEventListener('change', function() {
  alert(this.value);
}, false);

Its working as expected, as per 'change event' works when HTMLElement changes its value.它按预期工作,当 HTMLElement 更改其值时,根据“更改事件”工作。 With your 'select' element, it will not change its value when you select the same value is already selected.使用您的“选择”元素,当您 select 已选择相同的值时,它不会更改其值。

You can add a default 'Select your value...' or something else you want, to prevent this behavior and accomplish what you are looking for.您可以添加默认的“选择您的值...”或您想要的其他内容,以防止这种行为并完成您正在寻找的内容。

HTMLElement: change event HTMLElement:更改事件

 var a = document.getElementById('country'); a.addEventListener('change', function() { if (this.value === 'default') return; alert(this.value); }, false);
 <select id="country" > <option value="default">Select country</option> <option value="india">India</option> <option value="australia">Australia</option> <option value="turkey">Turkey</option> </select>

You can add a default <option> like the the following:您可以添加一个默认的<option> ,如下所示:

<option selected disabled>DEFAULT</option>

Or you can use a more direct event like "click"或者您可以使用更直接的事件,例如“点击”

 document.querySelector('#country').addEventListener('click', function(e) { document.querySelector('#view').value = this.value; });
 <output id='view'></output><br> <select id="country" > <option value="india">India</option> <option value="australia">Australia</option> <option value="turkey">Turkey</option> </select>

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

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