jQuery .on('change',function(){}不触发动态创建的输入


147

问题是我有一些动态创建的输入标签集,并且我还有一个函数,该函数可以在输入值更改时随时触发。

$('input').on('change', function() {
  // Does some stuff and logs the event to the console
});

但是,.on('change')不会为任何动态创建的输入触发,仅针对页面加载时存在的项目触发。不幸的是,这让我有点束缚,因为.on它打算替代它,.live().delegate()所有这些都是包装.bind():/

其他人有这个问题或知道解决方案吗?

Answers:


272

您应该为on函数提供选择器:

$(document).on('change', 'input', function() {
  // Does some stuff and logs the event to the console
});

在这种情况下,它将按预期工作。另外,最好指定一些元素而不是文档。

阅读这篇文章可以更好地理解:http : //elijahmanor.com/differences-between-jquery-bind-vs-live-vs-delegate-vs-on/


1
你真棒!我也有这个问题。没想到您可以将选择器添加为第二个参数。
Tomatrox

1
是的,它指出缩小到某个元素而不是整个文档是有益的,如果动态部分在某个div之后使用该元素,例如:$('#ajax_table')。on('change','input ',function(){...
Raul Gomez

3
如果我的元素很神秘,我以后如何使用它?$这给了我空的对象。
aleXela 2016年

它像一种魅力。非常感谢 !此外,我们可以使用.once()来防止添加两次相同的逻辑;)
benftwc

备用语法:$(document).on({ change: handleChange }, 'input');加上函数const handleChange = (event) => { $(event.target)...避免麻烦就很好了this
Dem Pilafian

23

用这个

$('body').on('change', '#id', function() {
  // Action goes here.
});

仅供参考,@ enrey $('#id')在代码中引用而不是'#id'
Loaf

14

您可以采用任何一种方法:

$("#Input_Id").change(function(){   // 1st
    // do your code here
    // When your element is already rendered
});


$("#Input_Id").on('change', function(){    // 2nd (A)
    // do your code here
    // It will specifically called on change of your element
});

$("body").on('change', '#Input_Id', function(){    // 2nd (B)
    // do your code here
    // It will filter the element "Input_Id" from the "body" and apply "onChange effect" on it
});

3
$("#id").change(function(){
    //does some stuff;
});

11
嗯...片段的解释如何?
kleopatra

12
这仍然无法与动态创建的元素一起使用,因为它会尝试在文档加载时进行绑定。但是,@ ArtemVyshniakov的答案绑定到文档,并且当其中一个元素中的某项更改时,它会被触发,由于第二个参数,它可以针对所需元素。(这意味着当函数触发时,它将检查触发器的源是否与第二个参数匹配)
FullyHumanProgrammer15年

在使用预加载的DOM之前,此代码将不起作用。您必须将选择器作为与文档相关的变量api.jquery.com/on/#on-events-selector-data传递
benftwc

2

只是为了澄清一些潜在的混乱。这仅在DOM加载中存在元素时才有效:

$("#target").change(function(){
    //does some stuff;
});

以后动态加载元素时,可以使用:

$(".parent-element").on('change', '#target', function(){
   //does some stuff;
});


1

您可以使用“输入”事件,该事件在元素获取用户输入时发生。

$(document).on('input', '#input_id', function() {
  // this will fire all possible change actions
});

w3的文档


By using our site, you acknowledge that you have read and understand our Cookie Policy and Privacy Policy.
Licensed under cc by-sa 3.0 with attribution required.