简体   繁体   中英

How to add data toggle to link tag if ul is present in the li

Please see the below code i have for my main menu on my website.

I want to add a data-toggle to the link tag for the dropdown but when the li doesnt contain ul I dont want the data-toggle added to the a tag. Would jquery be able to do this?

I am using bootstrap for this but in my menu I have menu links with no dropdown and the link url i add doesnt work as its expecting a dropdown to appear, if there a way around this?

<ul class="nav navbar-nav"> <li class="dropdown yamm-fw"> <a href="#" class="dropdown-toggle">Menu 1</a> <ul class="dropdown-menu"> <li><a href="#">Menu Item</a></li> </ul> </li> <li class="dropdown yamm-fw"> <a href="#" class="dropdown-toggle">Menu 2</a> </li> <li class="dropdown yamm-fw"> <a href="#" class="dropdown-toggle">Menu 3</a> </li> <li class="dropdown yamm-fw"> <a href="#" class="dropdown-toggle">Menu 4</a> </li> <li class="dropdown yamm-fw"> <a href="#" class="dropdown-toggle">Menu 5</a> </li> </ul>

Try this:

$('.dropdown').each(function() {
    if ($(this).find('UL').length === 0) {
        $(this).find('A').data('toggle', true);
    }
});

更好的做法是,ul.nav内部任何具有子ul的li都将添加数据切换。

$("ul.nav li ul").parent().attr("data-toggle","")

You could also use the :has selector

$(function() {
    $(".dropdown:has(ul) a").attr("data-toggle", /*value here*/);
});

Both answers are correct, this is just another option using the :has selector. It's also a one-liner :)

$("ul.nav > li:has(ul) a").attr("data-toggle","");

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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