javascript - 当点击 sub li 时,点击功能被调用两次。我该如何解决?

标签 javascript jquery html css cordova

我在 jquery 中动态创建菜单。我创建了一个父 ulli 并且它工作正常。如果我将 ul 附加到任何 li 它被附加但是当我点击那个 child li 我无法获得 id ulli 中的任何一个。我把 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/

相关文章:

html - 一个网页可以有多长?

javascript - 以php形式调用javascript函数

javascript - 如果刷新或选项卡关闭,Dropzone 将删除文件

javascript - 如何通过单击一次从两个不同的 div(其中一个隐藏)复制内容,但每个 div 都在单独的行上?

javascript - 有人可以解释以下 javascript 代码吗?

PHP/HTML/CSS/FileMaker PHP API 条件格式 <td>

html - 为什么 http-equiv ="X-UA-Compatible"内容 ="IE=edge,chrome=1"没有在 W3C Validator 中验证?

javascript - 如何让我的 js 文件同时适用于 ES6 模块和普通 js?

javascript - 元素的 readyState 是 HAVE_NOTHING

javascript - 将属性应用于多个对象