1

クリック機能は、動的に追加された html では機能しません。クラスは新しい要素で true としてテストされますが、そのクラスのクリック機能は無視されますが、他の要素では正常に機能しています。

関連するコードは次のとおりです。

// The added html element + addClass
$('#sendResultMsg').html('<a href="javascript:void(0);" id="closeButt">Close</a>');
$('#sendResultMsg').find('#closeButt').addClass('closeButton');

// just for testing this alert confirms hasClass as true
alert($('#closeButt').hasClass('closeButton'));

「#sendresult」はページ内の要素であり、html は「閉じる」リンクで正常に表示されますが、クリックしても何も起こりません。クラスに割り当てられたクリック機能は、ページ内の他の 2 つの要素で正常に機能し、次のようになります。

$('.toggleContactBox, .closeButton).on('click',function () {
  cntBox = $('#contactBox');
  cntBoxPos = cntBox.css('right');
  if (cntBoxPos <= '-550px') {
    cntBox.animate({ right: '0px' }, 200);
  } else {
    cntBox.animate({ right: '-550px' }, 200);
  }
});
4

4 に答える 4

2

イベントを動的に追加された要素にバインドするに.onは、DOMドキュメントに存在する上位の要素にイベントを委任する必要があります

試す

$(document).on('click','.toggleContactBox, .closeButton',function () {
  cntBox = $('#contactBox');
  cntBoxPos = cntBox.css('right');
  if (cntBoxPos <= '-550px') {
    cntBox.animate({ right: '0px' }, 200);
  } else {
    cntBox.animate({ right: '-550px' }, 200);
  }
});
于 2013-03-13T10:43:19.913 に答える
0

交換

$('.toggleContactBox, .closeButton).on('click',function () {

$('.toggleContactBox, .closeButton').on('click',function () {

'クラスセレクターをいつ使用したか忘れました。

于 2013-03-13T10:45:37.433 に答える
0

次のように変更します。

$('#sendResultMsg').on('click', '.toggleContactBox, .closeButton', function () {
    ...
});

ドキュメント: http://api.jquery.com/on/

If selector is omitted or is null, the event handler is referred to as direct or directly-bound. The handler is called every time an event occurs on the selected elements, whether it occurs directly on the element or bubbles from a descendant (inner) element.

When a selector is provided, the event handler is referred to as delegated. The handler is not called when the event occurs directly on the bound element, but only for descendants (inner elements) that match the selector. jQuery bubbles the event from the event target up to the element where the handler is attached (i.e., innermost to outermost element) and runs the handler for any elements along that path matching the selector.

于 2013-03-13T10:45:41.453 に答える