jQuery 隐藏输入更改事件

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/12580761/
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 11:49:41  来源:igfitidea点击:

hidden input change event

jqueryinputhidden

提问by chokrijobs

How can I detect a change of the value of a hidden input? I've already tried these approaches without success:

如何检测隐藏输入值的变化?我已经尝试过这些方法但没有成功:

$('#id_inpout').live('change',function () {
        var id_el = $(this).attr('id');
        alert(id_el);
    });

and

$('#id_inpout').change(function () {
        var id_el = $(this).attr('id');
        alert(id_el);
    });

and

$('#id_inpout').bind('change',function () {
        var id_el = $(this).attr('id');
        alert(id_el);
    });

回答by Alex

You could also use trigger('change')after you assign new value to the hidden input:

您还可以trigger('change')在为隐藏输入分配新值后使用:

$('#hidden_input').val('new_value').trigger('change');

回答by Denys Séguret

As was said in duplicates, and as you saw, changes done in javascript don't trigger the changeevent.

正如重复中所说的,正如您所看到的,在 javascript 中所做的更改不会触发该change事件。

As I didn't find acceptable answers in the duplicates (that is answers not involving a change in the way the hidden value is set), and supposing you really need that(that is you can't call your function when you change the hidden input val), here's what you might do :

因为我没有在重复项中找到可接受的答案(即答案不涉及更改隐藏值的设置方式),并且假设您确实需要那个(也就是说,当您更改隐藏值时,您无法调用您的函数输入 val),这是您可以执行的操作:

function survey(selector, callback) {
   var input = $(selector);
   var oldvalue = input.val();
   setInterval(function(){
      if (input.val()!=oldvalue){
          oldvalue = input.val();
          callback();
      }
   }, 100);
}
survey('#id_inpout', function(){console.log('changed')}); 

But I would preferably use a more direct solutions (i.e. call a function when you change the hidden input value). This function might be a simple event dispatcher of your own (basically an object wrapping a list of functions to call when it's called).

但我最好使用更直接的解决方案(即在更改隐藏输入值时调用函数)。这个函数可能是你自己的一个简单的事件调度器(基本上是一个对象,它包装了一个在调用时要调用的函数列表)。

EDIT:It's now 2015 and for people wondering, no, none of the recent advances of the web world solve that problem. Mutation observers don't observe the value property of the input (it's not really the DOM) and ES6 object observer are powerless for those native objects too.

编辑:现在是 2015 年,人们想知道,不,网络世界的最新进展都没有解决这个问题。Mutation 观察者不观察输入的 value 属性(它不是真正的 DOM)并且 ES6 对象观察者对这些原生对象也无能为力。