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 与 'Close' 链接一起显示很好,但单击时没有任何反应。分配给该类的单击功能在页面中的其他 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 回答
0

而不是“开”使用现场,它会工作

于 2013-03-13T11:00:10.190 回答