本文介绍了未在动态li元素上触发事件的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
在页面加载时,我正在使用以下方法在Jquery中创建水平选项卡:
On load of the page, I'm creating horizontal tabs in Jquery using:
function createhorizontaltab(categories) {
var categoryArr = JSON.parse(categories);
var htmlbuild = $('<ul>');
for (var i = 0; i < categoryArr.categories.length; i++) {
var name = categoryArr.categories[i].name;
htmlbuild.append('<li id= "'+name+'" class="active">'+name+'</a></li>');
}
htmlbuild.append('</ul>');
$("#menuInner").append(htmlbuild);
}
我的HTML代码:
<body>
<section class="menuWrap">
<div id = "menuInner" class="menuInner">
</div>
</section>
</body>
我正在尝试通过这种方式选择的li的click事件进行注册,但这并没有引起人们的注意.
I'm trying to register with the click event of li selected this way, but this is not getting fire up.
我需要将其保留在 jQuery ready()函数之外:
I need to keep this outside the Jquery ready() function:
$(document).ready(function () {
createhorizontaltab(categories)
}
$("#menuInner li ").click(function(){
}
有人可以帮我吗?
推荐答案
使用此
$(document).on( "click", "#menuInner li", function() {
//
});
on() -事件委托
on() - Event delegation
或
$(document).delegate( "#menuInner li", "click", function() {
//
});
delegate() -将处理程序附加到一个或多个事件现在或未来中在选择器中指定的元素.
delegate() - Attaches a handler to one or more events for elements specified in the selector, now or in the future.
您正在动态添加元素.
这篇关于未在动态li元素上触发事件的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!