Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
530 views
in Technique[技术] by (71.8m points)

javascript - Is there a workaround to trigger an option.click event in IE?

I am using a dropdown to allow the user to sort search results. These results in a table but not all of the sortable criteria are represented by columns. The columns can be sorted by either clicking on the column header or using a 'Sort By' dropdown. The user can reverse the sort by clicking on the sorted columns header. I am trying to duplicate this functionality in the drop down but can't get it to work in IE7/IE8.

The following is the existing code that works in both IE and Firefox. It changes the sorted column but not the sort direction.

$("#sortSelect").change(function() {
    //change sort
});

This is what I am trying to change it to and it works in Firefox. It changes the sorted column and if the sorted columns is already selected it will change the sort direction.

$("#sortSelect option").click(function() {
    //change sort
});

I was hoping someone would know of a way to trigger the option.click event or know of a good workaround.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

To reiterate what T.J. Crowder said in the comments, this is an awkward change that you're making to a user interface. That being said, it's possible to distinguish between clicking on the select element and clicking on an option element if the select doesn't have the multiple attribute set. Try out the following code in Internet Explorer:

$(document).ready(function ()
{
  $("#sortSelect").click(function (event) {
    if (event.offsetY > this.offsetHeight)
      $(this.options[this.selectedIndex]).click();
  });
  $("#sortSelect option").click(function (event)
  {
    alert('clicked option '+this.parentNode.selectedIndex);
  });
});

It works because when you click on an option element, the click event fires on the select element. By detecting that you've clicked outside the bounds of the select element checking event.offsetY > this.offsetHeight, you can use jQuery to trigger the click event of the currently selected option element.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...