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

Nic*_*ck 139 javascript jquery

问题是我有一些动态创建的输入标签集,我还有一个功能,可以在输入值改变时触发.

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

但是,.on('change')不会触发任何动态创建的输入,仅适用于加载页面时存在的项目.不幸的是,这让我有点像一个绑定,因为.on它意味着替换.live(),.delegate()所有这些都是包装器.bind():/

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

Art*_*kov 249

你应该为on函数提供一个选择器:

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

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

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

  • 如果我的元素是dinamicaly,我怎么能在以后使用它?$ this给了我空的对象. (3认同)

Dix*_*xon 19

用这个

$('body').on('change', '#id', function() {
  // Action goes here.
});
Run Code Online (Sandbox Code Playgroud)


Ars*_*mad 12

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

$("#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
});
Run Code Online (Sandbox Code Playgroud)


小智 9

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

$("#target").change(function(){
    //does some stuff;
});
Run Code Online (Sandbox Code Playgroud)

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

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