选择的jQuery更改事件不是通过其他函数更改选定属性触发的。

时间:2021-04-29 23:58:35

HTML

HTML

<select multiple="multiple" id="myID" name="myName">
    <option value="blue">blue</option>
    <option value="red">red</option>
    <option value="green">green</option>                
</select>

jQuery:

jQuery:

$('select')
    .change(function(){
        alert("Change Event Triggered On:" + $(this).attr("value"));
    })

That, as is, works. If I click an item in the multiselect, the alert is triggered.

是,工作。如果我单击multiselect中的一个项目,就会触发警报。

However, when I 'select' an element from the select menu via jQuery like so:

但是,当我通过jQuery从select菜单中“选择”一个元素时,如下所示:

$('#myOtherSelector')
    .click(function(){
        var $matchingOption = [goes and selects the specific OPTION to toggle]
        if ($matchingOption.attr("selected")){
            $matchingOption.removeAttr("selected")
        }else{
    $matchingOption.attr("selected","selected");
        }
    })

That script works in that it changes the SELECTED attribute and visually updates the option list, however the onchange event doesn't get triggered in that scenario.

该脚本的工作原理是,它更改所选的属性并可视地更新选项列表,但是在该场景中不会触发onchange事件。

Why is that?

这是为什么呢?

1 个解决方案

#1


11  

Changing elements with code like that just doesn't trigger event handlers. You can do it yourself however:

使用这样的代码更改元素不会触发事件处理程序。但是你可以自己做:

else {
  $matchingOption.attr('selected', 'selected').trigger('change');
}

#1


11  

Changing elements with code like that just doesn't trigger event handlers. You can do it yourself however:

使用这样的代码更改元素不会触发事件处理程序。但是你可以自己做:

else {
  $matchingOption.attr('selected', 'selected').trigger('change');
}