Event attached to Option node not being fired

二次信任 提交于 2020-01-16 09:59:31

问题


I have this code

    var option = new Option(thatOption.text, thatOption.value);
    $(option).click( function(){
                //Sorry cannot reveal what is here I'll just use this so that it can be referenced
                alert("clicked");
            }
        );

    try{
        selectBox.add(option,null);
    }catch(e){
        // Stupid IE doesn't know how to follow the spec
        selectBox.add(option);
    }

This code works in FF > 2 (don't have FF 1 oe FF 2 to test), Opera (presto), Chrome (webkit) and doesn't work on IE. When I click the option in the selectbox nothing happens. No event seems to be launched simply, nothing!
Question. How can I solve that?
Objective: (according to that code) make the alert appear
BTW: Why does that happen?
Extra note: The developer tools state that there are no errors involved.


回答1:


Why does that happen?

The root cause of this has been discussed a few times already on SO:

  • option & jQuery .click() won't work together
  • click event for option doesn't work in IE
  • Click on option event
  • etc.

Older versions of IE simply don't support click events on <option> elements. Instead, you'll have to listen to the <select>'s change (or click) event:

$(selectBox).change(function () {
});

Regarding your specific task, to have the alert appear (or your actual code execute) only when that option is selected, you can test if the option is selected within the change event:

var option = new Option(thatOption.text, thatOption.value);

$(selectBox).change(function () {
    if ($(option).is(':selected')) {
        alert('clicked');
    }
});

If you don't have the option variable at the ready, you can instead test with the value of the <select>:

$(selectBox).change(function () {
    if ($(this).val() === 'something') {
        alert();
    }
});

Also, to avoid the try..catch and Stupid IE doesn't know how to follow the spec, you can do just:

$(selectBox).append(option);


来源:https://stackoverflow.com/questions/7760177/event-attached-to-option-node-not-being-fired

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