簡體   English   中英

jQuery .on('change', function() {} 不會觸發動態創建的輸入

[英]jQuery .on('change', function() {} not triggering for dynamically created inputs

問題是我有一些動態創建的輸入標簽集,而且我還有一個函數可以在輸入值改變時觸發。

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

但是.on('change')不會為任何動態創建的輸入觸發,僅適用於加載頁面時存在的項目。 不幸的是,這讓我有點.on因為.on旨在替代.live().delegate()所有這些都是.bind()包裝器:/

有沒有其他人遇到過這個問題或知道解決方案?

您應該為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/

用這個

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

您可以使用以下幾種方法中的任何一種:

$("#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
});

您可以使用:

$('body').ready(function(){
   $(document).on('change', '#elemID', function(){
      // do something
   });
});

它和我一起工作。

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

只是為了澄清一些潛在的混淆。 這僅在 DOM 加載時存在元素時才有效:

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

當稍后動態加載元素時,您可以使用:

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

function aFunc() {
  // code here...
}

您可以使用 'input' 事件,該事件在元素獲得用戶輸入時發生。

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

來自w3 的文檔

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM