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

2022-08-30 02:00:59

问题是我有一些动态创建的输入标记集,我还有一个函数,旨在在输入值更改时触发。

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

但是,不会针对任何动态创建的输入触发 ,而只会触发加载页面时存在的项。不幸的是,这让我有点束缚,因为这意味着要成为替代品,所有这些都是包装器:/.on('change').on.live().delegate().bind()

是否有其他人遇到过这个问题或知道解决方案?


答案 1

您应该为函数提供一个选择器: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/


答案 2

您可以使用以下几种方法中的任何一种:

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


$("#Input_Id").on('change', function(){    // 2nd way
    // do your code here
    // This will specifically call onChange of your element
});

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