我在 jquery
中动态创建菜单。我创建了一个父 ul
和 li
并且它工作正常。如果我将 ul
附加到任何 li
它被附加但是当我点击那个 child li
我无法获得 id ul
或 li
中的任何一个。我把 id 给了那个 child li
。我什至尝试使用 li
id 或 class 编写点击操作,但也不起作用。请找到以下代码。
谁能帮帮我?
从上图中,我想在单击类别 1 时获取类别 1 的 ID。
HTML:
<ul id="menu"> </ul>
脚本:
$("#menu").on("click", "li", function () {
$("#menu ul").empty('');
var html = "<ul class='sub_ul'>";
var abc = subArrays[$(this).attr('id')];
for(var i = 0; i < abc.length; i++) {
if(abc[i] != ' ') {
html = html + "<li class='sub_first_li' id='sub_" + $(this).attr('id') + "_" + i + "'><a class='sub_first_li' href='#'>" + abc[i] + "</a></li>";
}
html = html + "</ul>";
$(this).append(html);
$("#menu ul").css({
'display': 'block'
});
});
});
更新:
现在我得到了更正的 li id 但是当我点击任何 li(category1) 函数时
会开火两次。我需要做什么才能打一次电话?任何人都可以帮助我..
最佳答案
当您动态生成 li
时。
您需要使用 Event Delegation .你必须使用 .on()使用委托(delegate)事件方法。
即(一般例子)
$(document).on('event','selector',callback_function)
为你
$("#menu").on('click', "li", function(){
//Your code
});
事件处理程序只绑定(bind)到当前选中的元素;在您的代码进行事件绑定(bind)调用时,它们必须存在于页面上。
The delegated events have the advantage that they can process events from descendant elements that are added to the document at a later time. By picking an element that is guaranteed to be present at the time the delegated event handler is attached, we can use delegated events to bind the click event to dynamically created elements and also to avoid the need to frequently attach and remove event handlers.
关于javascript - 当点击 sub li 时,点击功能被调用两次。我该如何解决?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/24408608/