我有一个水平类别栏。这是由 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">↓</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/