javascript - jquery - 动态菜单 - 单击功能不起作用

标签 javascript jquery

我有一个水平类别栏。这是由 php 填充的 - 我在 anchor 上设置了 data-cat-id 属性。然后使用 jquery click 函数来获取这个值,如下所示:

        $('.filterCat').click(function() {
            alert('cat id is:'+$(this).data("cat-id"))
            return false;
        });

这很好用。但是水平栏有一个功能,当宽度小于其内容时,可以将列表元素添加到“更多”子菜单中。使用代码:

$(函数() {
对齐菜单();

$(window).resize(function() {
  $("#horizontal").append($("#horizontal li.hideshow ul").html());
  $("#horizontal li.hideshow").remove();
  alignMenu();
});

function alignMenu() {
  var w = 0;
  var mw = $("#horizontal").width() - 150;
  var i = -1;
  var menuhtml = '';
  jQuery.each($("#horizontal").children(), function() {
    i++;
    w += $(this).outerWidth(true);
    if (mw < w) {
      menuhtml += $('<div>').append($(this).clone()).html();
      $(this).remove();
    }
  });
  $("#horizontal").append(
    '<li  style="position:relative;" href="#" class="hideshow">' + '<a href="#">More ' + '<span style="font-size:13px">&#8595;</span>' + '</a><ul>' + menuhtml + '</ul></li>');
  $("#horizontal li.hideshow ul").css("top",
    $("#horizontal li.hideshow").outerHeight(true) + "px");
  $("#horizontal li.hideshow").click(function() {
    $(this).children("ul").toggle();
  });
  if (menuhtml == '') {
    $("#horizontal li.hideshow").hide();
  } else {
    $("#horizontal li.hideshow").show();
  }
}

});

这也有效,但现在当有“更多”按钮时(因为内容更大),点击功能不再起作用。

我做了一个 fiddle - 如果您单击普通菜单项,它会显示警报,但如果您单击“更多”下的项目,它不会看到 FIDDLE:https://jsfiddle.net/quosa60e/

最佳答案

对于动态创建的元素.click()不起作用

document.on('click','SELECTOR',function(){});

所以你应该使用:

$(document).on('click','.filterCat',function() {
    alert('cat id is:'+$(this).data("cat-id"))
    return false;
});

关于javascript - jquery - 动态菜单 - 单击功能不起作用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42599589/

相关文章:

javascript - 如果ajax请求完成调用函数

.net - 如何将 JScript Closure 转换为 JScript 中的 .NET 委托(delegate)?

javascript - 位置绝对图像在动画过程中只显示一半

jquery - slick.js 隐藏幻灯片直到点击屏幕上的元素

javascript - jQuery e.stopPropagation 与 body onclick 冲突

javascript - 将javascript添加到超链接

javascript - javascript中是否可以进行多重继承?

jquery - 如何创建自定义 JQuery 函数以及如何使用它?

javascript - 具有不同列数的数据表

javascript - 从文本编辑器将文章存储在数据库中的最佳方法