Функция щелчка с addClass не работает в динамическом html()

Функция щелчка не работает в динамически добавленном html. Класс проверяется в новом элементе как истинный, но он игнорирует функцию щелчка для этого класса, хотя в других элементах он работает нормально.

Вот соответствующий код:

// 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 отображается нормально со ссылкой "Закрыть", но при нажатии ничего не происходит. Функция щелчка, назначенная классу, отлично работает в двух других элементах на странице и выглядит следующим образом:

$('.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);
  }
});

person El Eme    schedule 13.03.2013    source источник


Ответы (4)


чтобы привязать событие к динамически добавляемым элементам с помощью .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);
  }
});
person Dakait    schedule 13.03.2013
comment
Нет необходимости привязывать событие к document, так как #sendResultMsg уже присутствует в DOM. - person iappwebdev; 13.03.2013
comment
я просто высказал свою точку зрения на оригинальный постер, как он это использует - person Dakait; 13.03.2013

Заменить

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

С

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

Вы забыли ', когда использовали селектор класса.

person Devang Rathod    schedule 13.03.2013
comment
Откуда вы знаете, что .closeButton находится внутри .toggleContactBox? - person iappwebdev; 13.03.2013
comment
Я пропустил закрывающую запятую в посте, но она есть в коде. Это два разных класса, которые выполняют одну и ту же функцию щелчка, поэтому они разделены запятыми. В любом случае dakait дал мне решение, которое работает. попробую понять почему? и что отличается от моего подхода... все равно спасибо. - person El Eme; 13.03.2013

Измените его на:

$('#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.

person iappwebdev    schedule 13.03.2013

Вместо того, чтобы использовать в прямом эфире, он будет работать

person user1268130    schedule 13.03.2013