jQuery 1.4.2 Using .delegate() on a change event for a doropdown list

社会主义新天地 提交于 2019-12-08 03:46:57

问题


My problem is that I am not sure how to use .delegate for the following scenario:

our application has a voting system to which several rounds or steps can be added. every time a new step is added there is a list of options that defines how the round/step is to be won.


<select class="listOfOptions">
<option value="U">Unanimous</option>

<option value="M">Majority</option>
<option value="C" class="customOption"># of votes…</option>
</select>

now when an option is selected the following code runs


$(document).ready(function() {

  $('.listOfOptions').live('change', function() {
    if ($(this).find(':selected').attr('class') == 'customOption') {
      // DO SOMETHING!!
    }
    else {
      // DO SOMETHING ELSE
    }
  });

});

This code runs perfectly on every other browser except IE.

How would I use .delegate() on as a replacement of .live for this case?

Thank you.


回答1:


This would be the syntax used with .delegate() for this particular case. Notice that the 'listOfOptions' is the class of the drop-down list.


$('body').delegate('.listOfOptions', 'change', function() {
    if ($(this).find(':selected').attr('class') == 'customOption') {
      // DO SOMETHING!!    
    }
    else {
      // DO SOMETHING ELSE      
    }
  });

It works like a charm in all browsers.




回答2:


Don't forget to write the delegating in a $(function() {}); block or in $(document).ready(function() {});

It won't work in IE 7-9 otherwise.



来源:https://stackoverflow.com/questions/3588459/jquery-1-4-2-using-delegate-on-a-change-event-for-a-doropdown-list

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!