2

ドキュメントから

$(selector).live(events, data, handler);                // jQuery 1.3+
$(document).delegate(selector, events, data, handler);  // jQuery 1.4.3+
$(document).on(events, selector, data, handler);        // jQuery 1.7+

jQuery1.7.1を使用しています

これは、静的要素と動的にロードされる要素に対して機能します。

$("input").live("change", function () { alert("hello"); });

これは、静的要素に対しても機能しません。

$("document").on("change", "input", function () { alert("hello"); });

私は何が欠けていますか?

4

3 に答える 3

8

次のように書く

$(document).on("change", "input", function () { alert("hello"); });

パフォーマンスを向上させるために、常に存在するものとdocument置き換えることができます。好きcloser parent elementDOM

$('#closest_static_container_id').on("change", "input", function () { 
     alert("hello"); 
});

$("document")jQueryを使用すると、 likenode/tagという名前が検索され、実際のように何も見つかりません。document<document>documentobject

ただし、のノード/要素を$("body")そのまま使用できます。bodyDOM

于 2012-06-04T15:02:22.310 に答える
4

変化する:

$("document").on(...)

に:

$(document).on("change", "input", function () { alert("hello"); });

documentはオブジェクト(のプロパティwindow)であり、ノードタイプではありません。

$("document").on(...)

次のようなオブジェクト<document>内の要素を探しています。document

<document>

そして、おそらくあなたが今までに得たように、何もありません...

とにかく、のベストプラクティスonは、動的に追加された要素に最も近い静的要素を使用することです。

<div id='container-div-id'>
    <input />  ... this will be added later.
</div>

$('#container-div-id').on("change", "input", function () {
     alert("hello"); 
 });
于 2012-06-04T15:02:36.660 に答える
2

documentはオブジェクトであり、文字列として使用しています。したがってjQuery、それをcssセレクターとして使用しようとしますが、イベントハンドラーをアタッチするものは何も見つかりません。

これを試して。

$(document).on("change", "input", function () { alert("hello"); });
于 2012-06-04T15:05:09.250 に答える