gpt4 book ai didi

javascript - 检查子 div 是否为空以从父元素中删除属性

转载 作者:行者123 更新时间:2023-11-30 19:51:29 25 4
gpt4 key购买 nike

我有一个菜单,其中的子菜单项有下拉菜单,有些只是单个链接。我正在为触摸设备处理这个问题,我删除了具有下拉菜单的子菜单项的 href 属性。我想检查子元素是否为空以不删除 href 属性,以便这些链接有效。我尝试了很多东西,但无济于事。以下是我目前所拥有的,我似乎无法弄明白。

<li class="sub-menu-dropdown-toggle">
<a href="{{ link.url }}" class="nav-link nav-link-sub-menu">Menu Item</a>
<div class="sub-menu-dropdown">
<div class="row justify-content-between sub-menu-content">Some of these have content</div>
<div class="row justify-content-between sub-menu-content">Some of these have content</div>
<div class="row justify-content-between sub-menu-content"></div>
</div>
</li>
const $emptyContent = $('.sub-menu-content');       
const $noFollow = $('.nav-link-sub-menu');

if ($emptyContent.is(':empty').trim()) {
$noFollow.removeAttr('href');
}

最佳答案

使用纯 JavaScript,您可以检索所有 <li>使用 querySelectorAll() 的元素 方法,然后使用 forEach() 方法和 innerText() 属性检查下拉菜单是否为空。

如果下拉菜单不为空,您可以使用 removeAttribute() 属性删除 href来自子 anchor 链接的属性。


检查并运行以下代码片段以获得我上面描述的实际示例:

/* JavaScript */

var lists = document.querySelectorAll(".sub-menu-dropdown-toggle");

lists.forEach(list => {
if (list.children[1].innerText.length > 0) { // check if the dropdown div has any text inside or not
list.children[0].removeAttribute("href"); // remove href attribute if it does
}
})
<!-- HTML -->

<ul>
<li class="sub-menu-dropdown-toggle">
<a href="abc.html" class="nav-link nav-link-sub-menu">Menu Item 1</a>
<div class="sub-menu-dropdown">
<div class="row justify-content-between sub-menu-content">Some of these have content</div>
<div class="row justify-content-between sub-menu-content">Some of these have content</div>
<div class="row justify-content-between sub-menu-content"></div>
</div>
</li>
<li class="sub-menu-dropdown-toggle">
<a href="abc.html" class="nav-link nav-link-sub-menu">Menu Item 2</a>
<div class="sub-menu-dropdown">
<div class="row justify-content-between sub-menu-content"></div>
<div class="row justify-content-between sub-menu-content"></div>
<div class="row justify-content-between sub-menu-content"></div>
</div>
</li>
<li class="sub-menu-dropdown-toggle">
<a href="abc.html" class="nav-link nav-link-sub-menu">Menu Item 3</a>
<div class="sub-menu-dropdown">
<div class="row justify-content-between sub-menu-content">Some of these have content</div>
<div class="row justify-content-between sub-menu-content">Some of these have content</div>
<div class="row justify-content-between sub-menu-content"></div>
</div>
</li>
</ul>

关于javascript - 检查子 div 是否为空以从父元素中删除属性,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54420151/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com