当通过JS更改值时,jQuery选择不触发onchange事件 [英] jQuery Chosen not firing onchange event when value is changed through JS

查看:133
本文介绍了当通过JS更改值时,jQuery选择不触发onchange事件的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我在小提琴中设置了一个选择,其中包含3 选项 s(1个空格)。当我手动从 foo 切换到 bar 时,更改听众正常开火。

I've set up a select with 3 options (1 blank) in the fiddle. When I switch from foo to bar manually, the change listener fires normally.

现在如果我通过JS重置选择并使用在这里的一些答案中公布了代码更改事件不会针对新选择的事件触发空白选项,此外,如果我选择在单击重置按钮之前选择的选项 onchange event won'也好了。

Now if I reset the select through JS with the code posted in some answers here, the change event does not fire for the newly selected blank option, furthermore, if I select the option which was selected before clicking in the reset button the onchange event won't fire either.

我确定选择的值 正在改变了上面的功能,可以在 小提琴 ,但选择 onchange 事件根本不会触发。

I'm sure the select's value is being changed with the function above, which can be seen in this fiddle, but the select's onchange event simply doesn't fire.

我也试过 onchange onclick oninput 事件无济于事。现在我想知道我是否应该使用MutationObserver或从DOM中删除渲染的选定元素并创建另一个,但我可能会过度思考它。任何帮助表示赞赏。

I've also tried onchange, onclick, oninput events to no avail. Right now I'm wondering if I should use a MutationObserver or remove the rendered chosen element from the DOM and create another, but I'm probably overthinking it. Any help is appreciated.

另外:

这个答案对我有很大帮助: jQuery选择重置

This answer helped me a lot: jQuery Chosen reset

这个答案没有帮助:如何在选择的原型javascript选择框中触发onchange事件?

如果jsfiddle.net被删除,将来参考的代码:

Code for future reference if jsfiddle.net is taken down:

HTML

<div id="wrapper">
    <select id="chosen">
        <option value="!!EMPTY VALUE!!"></option>
        <option value="foo">foo</option>
        <option value="bar">bar</option>
    </select>
</div>
<br>
<button id="reset">Reset</button>

JS

$(function() {
    $('#chosen').chosen();

    $('#wrapper').on('change', '#chosen', function() {
        console.log('onchange: ' + this.value);
    });

    $('#reset').click(function() {
        $("#chosen").val('').trigger("liszt:updated"); //doesn't work
        //$("#chosen").prop('selectedIndex', 0).trigger("liszt:updated"); //doesn't work either
        console.log('reset: ' + $('option:selected').val());
    });
});


推荐答案

更改值后需要触发更改与 $(选择器).trigger(更改)

You need to trigger the change after you change the value with $(selector).trigger("change")

$('#reset').click(function() {
        $("#chosen").val('').trigger("change"); //doesn't work
        //$("#chosen").prop('selectedIndex', 0).trigger("liszt:updated");
        console.log('reset: ' + $('option:selected').val());
    });

这篇关于当通过JS更改值时,jQuery选择不触发onchange事件的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆