【问题标题】:jquery - dynamic menu - click function not workingjquery - 动态菜单 - 单击功能不起作用
【发布时间】:2017-03-05 02:20:39
【问题描述】:

我有一个水平类别栏。这是由 php 填充的 - 我在锚点上设置了一个 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:https://jsfiddle.net/quosa60e/

【问题讨论】:

    标签: javascript jquery


    【解决方案1】:

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

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

    所以你应该使用:

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

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2020-12-10
      相关资源
      最近更新 更多