I want to fire a click event(not change event) on select option tags. Click event on select option tag only works in firefox not in google chrome. I have spend a lot of time to resolve this issue still not successfull. Anyone can help me to resolve this problem. Thanx in advance.
可以将文章内容翻译成中文,广告屏蔽插件可能会导致该功能失效(如失效,请关闭广告屏蔽插件后再试):
问题:
回答1:
Try editing the onclick
function of the select
tag to call to the option
tag's onclick
. The problem now is that it may call twice in FireFox.
function getSelectedOption(select) {
return select.options[select.selectedIndex];
}
To see in action ->
<select onclick='getSelectedOption(this).click()'>
<option onclick='log("foo")' >foo</option>
<option onclick='log("bar")' >bar</option>
</select>
<p id="display"></p>
<script>
function log(text) {
document.getElementById('display').innerHTML = text;
}
function getSelectedOption(select) {
return select.options[select.selectedIndex];
}
</script>
Also, the problem with this is that the onclick
is fired once for clicking the option and another for selecting (then firefox comes around for another). So, the best way I found to patch this is to change it to an onchange
for the select
tag.
But sadly that only gets rid of the initial click, not FireFox's correct way of clicking...
So, if we modify our getSelectedOption
function to check if the browser is chrome then we can cover our selves!
var is_chrome = navigator.userAgent.toLowerCase().indexOf('chrome') > -1;
Our new function can look like the following...
clickSelectedOption(select) {
if(!is_chrome) return;
select.options[select.selectedIndex].click();
}
Mix everything together!
<select onchange='clickSelectedOption(this)'>
<option onclick='log("foo")' >foo</option>
<option onclick='log("bar")' >bar</option>
</select>
<p id="display"></p>
<script>
var is_chrome = navigator.userAgent.toLowerCase().indexOf('chrome') > -1;
function log(text) {
document.getElementById('display').innerHTML = text;
}
function clickSelectedOption(select) {
if(!is_chrome) return;
select.options[select.selectedIndex].click();
}
</script>