Click event is not working on html select option t

2019-08-25 03:33发布

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条回答
不美不萌又怎样
2楼-- · 2019-08-25 04:10

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>

查看更多
登录 后发表回答