val() 不会触发 jQuery 中的 change()

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/3179385/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-26 14:58:42  来源:igfitidea点击:

val() doesn't trigger change() in jQuery

jquerytriggers

提问by Ergec

I'm trying to trigger the changeevent on a text box when I change its value with a button, but it doesn't work. Check this fiddle.

change当我使用按钮更改其值时,我试图在文本框上触发该事件,但它不起作用。检查这个小提琴

If you type something in the text boxes and click somewhere else, changeis triggered. However, if you click the button, the text box value is changed, but changedoesn't trigger. Why?

如果您在文本框中键入内容并单击其他位置,change则会触发。但是,如果单击该按钮,文本框值会更改,但change不会触发。为什么?

回答by djdd87

onchangeonly fires when the user types into the input and then the input loses focus.

onchange仅在用户输入输入然后输入失去焦点时触发。

You can manually call the onchangeevent using after setting the value:

您可以onchange在设置值后手动调用事件:

$("#mytext").change(); // someObject.onchange(); in standard JS

Alternatively, you can triggerthe event using:

或者,您可以使用以下方法触发事件:

$("#mytext").trigger("change");

回答by Chris Fulstow

From redsquare's excellent suggestion, this works nicely:

从 redsquare 的优秀建议来看,这很好用:

$.fn.changeVal = function (v) {
    return this.val(v).trigger("change");
}

$("#my-input").changeVal("Tyrannosaurus Rex");

回答by Yaron U.

You can very easily override the valfunction to trigger change by replacing it with a proxy to the original valfunction.

您可以val通过将其替换为原始val函数的代理来轻松覆盖该函数以触发更改。

just add This code somewhere in your document (after loading jQuery)

只需在文档中的某处添加此代码(加载 jQuery 后)

(function($){
    var originalVal = $.fn.val;
    $.fn.val = function(){
        var result =originalVal.apply(this,arguments);
        if(arguments.length>0)
            $(this).change(); // OR with custom event $(this).trigger('value-changed');
        return result;
    };
})(jQuery);

A working example: here

一个工作示例:here

(Note that this will always trigger changewhen val(new_val)is called even if the value didn't actually changed.)

(请注意,即使值实际上没有改变,这也会changeval(new_val)被调用时触发。)

If you want to trigger change ONLY when the value actually changed, use this one:

如果您只想在值实际更改时触发更改,请使用以下命令:

//This will trigger "change" event when "val(new_val)" called 
//with value different than the current one
(function($){
    var originalVal = $.fn.val;
    $.fn.val = function(){
        var prev;
        if(arguments.length>0){
            prev = originalVal.apply(this,[]);
        }
        var result =originalVal.apply(this,arguments);
        if(arguments.length>0 && prev!=originalVal.apply(this,[]))
            $(this).change();  // OR with custom event $(this).trigger('value-changed')
        return result;
    };
})(jQuery);

Live example for that: http://jsfiddle.net/5fSmx/1/

现场示例:http: //jsfiddle.net/5fSmx/1/

回答by Timothy Gonzalez

You need to chain the method like this:

您需要像这样链接方法:

$('#input').val('test').change();

回答by Darin Dimitrov

No you might need to trigger it manually after setting the value:

不,您可能需要在设置值后手动触发它:

$('#mytext').change();

or:

或者:

$('#mytext').trigger('change');

回答by Jay Godse

It looks like the events are not bubbling. Try this:

看起来事件没有冒泡。尝试这个:

$("#mybutton").click(function(){
  var oldval=$("#mytext").val();
  $("#mytext").val('Changed by button');
  var newval=$("#mytext").val();
  if (newval != oldval) {
    $("#mytext").trigger('change');
  }
});

I hope this helps.

我希望这有帮助。

I tried just a plain old $("#mytext").trigger('change')without saving the old value, and the .changefires even if the value didn't change. That is why I saved the previous value and called $("#mytext").trigger('change')only if it changes.

我只尝试了一个普通$("#mytext").trigger('change')的旧值而不保存旧值,.change即使值没有改变也会触发。这就是为什么我保存了以前的值并$("#mytext").trigger('change')仅在它发生变化时才调用的原因。

回答by cieunteung

As of feb 2019 .addEventListener()is not currently work with jQuery .trigger()or .change(), you can test it below using Chrome or Firefox.

截至 2019 年 2 月,.addEventListener()目前无法使用 jQuery.trigger().change(),您可以在下面使用 Chrome 或 Firefox 对其进行测试。

txt.addEventListener('input', function() {
  console.log('not called?');
})
$('#txt').val('test').trigger('input');
$('#txt').trigger('input');
$('#txt').change();
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<input type="text" id="txt">

you have to use .dispatchEvent()instead.

你必须.dispatchEvent()改用。

txt.addEventListener('input', function() {
  console.log('it works!');
})
$('#txt').val('yes')
txt.dispatchEvent(new Event('input'));
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>

<input type="text" id="txt">

回答by Slipoch

I know this is an old thread, but for others looking, the above solutions are maybe not as good as the following, instead of checking changeevents, check the inputevents.

我知道这是一个旧线程,但对于其他人来说,上述解决方案可能不如以下解决方案,与其检查change事件,不如检查input事件。

$("#myInput").on("input", function() {
    // Print entered value in a div box
    $("#result").text($(this).val());
});

回答by Sky Yip

From https://api.jquery.com/change/:

https://api.jquery.com/change/

The changeevent is sent to an element when its value changes. This event is limited to <input>elements, <textarea>boxes and <select>elements. For select boxes, checkboxes, and radio buttons, the event is fired immediately when the user makes a selection with the mouse, but for the other element types the event is deferred until the element loses focus.

change当元素的值改变时,该事件被发送到元素。此事件仅限于<input>元素、<textarea>框和<select>元素。对于选择框、复选框和单选按钮,当用户使用鼠标进行选择时会立即触发该事件,但对于其他元素类型,该事件会推迟到该元素失去焦点时。