点击功能无法在动态添加的html中使用。该类在new元素中测试为true,但它忽略了该类的click函数 - 尽管它在其他元素中工作正常。
以下是相关代码:
// 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);
}
});
答案 0 :(得分:2)
为了使用.on
将事件绑定到动态添加的元素,您必须将事件委托给DOM中存在的更高元素docs
试
$(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);
}
});
答案 1 :(得分:0)
替换
$('.toggleContactBox, .closeButton).on('click',function () {
。通过强>
$('.toggleContactBox, .closeButton').on('click',function () {
使用班级选择器时忘了'
。
答案 2 :(得分:0)
将其更改为:
$('#sendResultMsg').on('click', '.toggleContactBox, .closeButton', function () {
...
});
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.
答案 3 :(得分:0)
而不是'on'使用直播,它将起作用