4

Hi I have a Ajax call that I'm doing with jQuery and was wondering what is the difference between these methods on selecting an element on click,

FIRST

$(this).on('click', 'button', function (){ });

SECOND

$('button').on('click', function (){ });

THIRD

$('button').click(function { });

My Ajax call selects new data from my database and updates the content on success and changes the data from a data object that I have on the button with an ID, the first on works but the second and third once both only work once and then it fails and I'm am wondering why, thanks a lot in advance!

4

4 に答える 4

0

ドキュメントから:

$('button').click(function { });

このメソッドは .on('click', handler) のショートカットです

だからそれは同じです:

$('button').on('click', function { });

$(this)との違い$('button')はスコープです。最初のケースでは、クロージャー内の要素のハンドラーを取得しました。次に、セレクターを使用します。これbuttonは、ドキュメント上のすべてのクリックイベントを添付することを意味します。

于 2013-06-15T22:00:26.523 に答える
0

.on() を使用して、まだ存在しない要素にイベントをバインドできます。たとえば、 ajax レスポンスを div に入れる場合、先にイベントを定義して div にバインドし、トリガーを他の要素に設定することができます。

例えば:

$('div').on('click','button',function(){});
于 2013-06-15T22:01:33.903 に答える
0

最初の 1 つが機能し、他の 2 つが機能しない理由は、おそらく ajax 呼び出しの後にボタンを上書きするときにイベントを上書きしているためです。これは、on() で委任を使用するという点全体を無効にします。ajax 呼び出しが完了したら、最初のものを使用するか、イベント ハンドラーを再作成します。

于 2013-06-15T22:06:01.173 に答える