为什么使用val()设置select的值时,jquery更改事件不会触发? [英] Why does the jquery change event not trigger when I set the value of a select using val()?

查看:216
本文介绍了为什么使用val()设置select的值时,jquery更改事件不会触发?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

change()事件处理程序中的逻辑当值由 val(),但当用户用鼠标选择一个值时它会运行。这是为什么?

 < select id =single> 
< option>单一< / option>
< option> Single2< / option>
< / select>

< script>
$(function(){
$(:input#single)。change(function(){
/ *使用val()时,逻辑不会执行* /
});
});

$(#single)。val(Single2);
< / script>


解决方案

因为 code>事件需要一个由用户发起的实际浏览器事件,而不是通过javascript代码。



执行此操作:

  $(#single)。val(Single2)。trigger('change'); 

  $( #单)VAL( Single2)改变()。; 


The logic in the change() event handler is not being run when the value is set by val(), but it does run when user selects a value with their mouse. Why is this?

<select id="single">
    <option>Single</option>
    <option>Single2</option>
</select>

<script>
    $(function() {
        $(":input#single").change(function() {
           /* Logic here does not execute when val() is used */
        });
    });

    $("#single").val("Single2");
</script>

解决方案

Because the change event requires an actual browser event initiated by the user instead of via javascript code.

Do this instead:

$("#single").val("Single2").trigger('change');

or

$("#single").val("Single2").change();

这篇关于为什么使用val()设置select的值时,jquery更改事件不会触发?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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