繁体   English   中英

JavaScript下拉列表不再起作用

[英]Javascript dropdown no longer working

我有以下代码: http : //jsfiddle.net/spadez/928Dj/39/

$("ul.opt").addClass("hidden");
$('#filter > li > a').on("click", function (e) {
    var cache = $(this).next('ul');
    $('#filter ul:visible').not(cache).hide();
    cache.toggle();
});

控制台中没有错误。 在我的html中,将form移到了ul之外,从中可以看到javascript仍然有效,但是单击链接时不再触发下拉菜单。 代码中的错误在哪里?

问题在于next()不是ul

next()将获得下一个同级,因为next()不是ul它( next("ul") )将不包含元素。

由于您要获取的ul是下一个兄弟姐妹的孩子,因此请尝试以下操作:

的jsfiddle

$("ul.opt").addClass("hidden");
$('#filter > li > a').on("click", function (e) {
    var cache = $(this).next('form').find("ul");
    $('#filter ul:visible').not(cache).hide();
    cache.toggle();
});

笔记:

看来这不会发生...但是如果您可能在aform之间有其他兄弟姐妹,则可以执行.nextAll('form') ,这将查看a之后的所有兄弟姐妹。 。

如果您可能在form具有多个级别的ul ,则可能要执行.children('ul')而不是.find('ul') ,这样,它将仅查看直接子级。


替代

这可能是我会做的方式,我对所有内容(js,html和css)做了一些小的更改:

的jsfiddle

$('.dropdown').on("click", function (e) {
    var cache = $(this).siblings('.opt');
    $('.opt:visible').not(cache).hide();
    cache.toggle();
});

我只是将代码中的第3行替换为

var cache = $(this).next('form').find('ul');

小提琴

或者,您可以使用以下方法:

$("ul.opt").addClass("hidden");
$('#filter > li > a').on("click", function (e) {
    var cache = $(this).next().children();
    $('#filter ul:visible').not(cache).hide();
    cache.toggle();
});

小提琴

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM