171

問題は、動的に作成された入力タグのセットがいくつかあり、入力値が変更されるたびにトリガーされる関数もあるということです。

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

ただし、.on('change')動的に作成された入力に対してはトリガーされず、ページが読み込まれたときに存在していたアイテムに対してのみトリガーされます。残念ながら、これは.on: /.live().delegate().bind()

他の誰かがこの問題を抱えているか、解決策を知っていますか?

4

8 に答える 8

310

on関数にセレクターを提供する必要があります。

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

その場合、期待どおりに動作します。また、ドキュメントではなく何らかの要素を指定した方がよいでしょう。

理解を深めるために、この記事を読んでください。

于 2012-11-16T14:53:33.020 に答える
25

いくつかのアプローチのいずれかを使用できます。

$("#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
});
于 2018-05-02T07:14:49.900 に答える
4
$("#id").change(function(){
    //does some stuff;
});
于 2015-09-01T12:41:51.417 に答える