2

jQuery (v1.8.18) の特定の要素にクリック イベントをバインドしようとしています。バインドを行っているときに存在するセレクターに一致する 2 つの要素がありますが、最終的にはセレクターに一致する 3 番目の要素もありますが、登録した後のある時点までマークアップされません。イベント。

私がちょうど使用するとき:

$('.collapsible h2 > .ui-icon').bind('click', toggleCollapsibleList);

...その後、事前に存在する2つに正しくバインドされますが、明らかに3番目のものにはバインドされません。私が使用する場合:

$('.collapsible h2 > .ui-icon').live('click', toggleCollapsibleList);

...そして、それらのどれも拘束されていません。そして、私が使用するとき:

$('.collapsible h2 > .ui-icon').on('click', toggleCollapsibleList);

...その後、.bind() と同じように動作します。3 つの要素すべてが DOM に存在し、ページの読み込みが完了した後にセレクターと一致することを開発者ツールで確認しました。私が間違っているかもしれないことを誰かが知っていますか?

4

2 に答える 2

3

jQueryは1.7.on()で導入されたため、廃止予定です。のように動作させたい場合、現在使用している方法は正しくありません。.live().on().live()

次のようなものを効果的に使用したい.on()

$(document).on('click', '.collapsible h2 > .ui-icon', toggleCollapsibleList);

以下は jQuery .live()docsからの抜粋です。

$(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+
于 2012-11-30T16:47:38.167 に答える
0
// These will attach an event handler for all elements which match the 
// current selector NOW
$('.collapsible h2 > .ui-icon').bind('click', toggleCollapsibleList);
// is equivalent to
$('.collapsible h2 > .ui-icon').on('click', toggleCollapsibleList);


// These will attach an event handler for all elements which match the 
// current selector NOW AND IN THE FUTURE

// not recommended
$('.collapsible h2 > .ui-icon').live('click', toggleCollapsibleList); 
// is equivalent to
// recommended
$(document).on('click', '.collapsible h2 > .ui-icon', toggleCollapsibleList); 
于 2012-11-30T17:06:59.267 に答える