将spesific属性添加到div中的锚标记

时间:2018-08-03 07:23:46

标签: javascript jquery html twitter-bootstrap

wordpress

中创建菜单时遇到一些问题

导航代码

<nav class="navbar navbar-inverse" id="sidebar-wrapper" role="navigation">
  <ul id="mobile" class="sidenav">
    <li class="menu-item menu-item-type-custom menu-item-object-custom current- 
     menu-item current_page_item menu-item-home menu-item-7"> <a href="http://localhost/test/">Home</a> </li>
    <li class="menu-item menu-item-type-post_type menu-item-object-page menu-item-13"> <a href="http://localhost/buildownwp/laman-contoh/">Laman Contoh</a> </li>
    <li class="menu-item menu-item-type-custom menu-item-object-custom menu-item-has-children menu-item-1159"> <a href="#" class="dropdown-toggle" id="navbarDropdown" data-toggle="dropdown" aria-haspopup="true" aria-expanded="false">et nulam</a>
      <ul class="sub-menu">
        <li class="menu-item menu-item-type-post_type menu-item-object-post menu-item-15"> <a href="http://localhost/buildownwp/tak-berkategori/halo-dunia/" class="dropdown-toggle" id="navbarDropdown" data-toggle="dropdown" aria-haspopup="true" aria-expanded="false">Halo dunia!</a> </li>
        <li class="menu-item menu-item-type-custom menu-item-object-custom menu-item-has-children menu-item-1161"> <a href="#" class="dropdown-toggle" id="navbarDropdown" data-toggle="dropdown" aria-haspopup="true" aria-expanded="false">second2</a>
          <ul class="sub-menu">
            <li class="menu-item menu-item-type-post_type menu-item-object-post menu-item-14"> <a href="http://localhost/buildownwp/tak-berkategori/lorem-ipsum/" class="dropdown-toggle" id="navbarDropdown" data-toggle="dropdown" aria-haspopup="true" aria-expanded="false">Lorem Ipsum</a> </li>
            <li class="menu-item menu-item-type-custom menu-item-object-custom menu-item-1160"><a href="#" class="dropdown-toggle" id="navbarDropdown" data-toggle="dropdown" aria-haspopup="true" aria-expanded="false">second</a> </li>
          </ul>
        </li>
      </ul>
    </li>
    <li class="menu-item menu-item-type-custom menu-item-object-custom menu-item-1158"> <a href="#">dolor sit amet</a></li>
  </ul>
</nav>

jQuery

$('.menu-item-has-children a').attr('class', 'dropdown-toggle').attr('id','navbarDropdown').attr('data-toggle','dropdown').attr('aria-haspopup','true').attr('aria-expanded','false');

如果具有class menu-item-has-children将添加属性,则该代码应像菜单一样显示;如果该菜单具有下拉菜单,但该代码的结果类似于nav-mobile < / p>

您好,请不要影响该代码,因为他没有子菜单/子菜单,非常感谢您能为我提供帮助

1 个答案:

答案 0 :(得分:1)

嗯,我知道您想在父项上限制查找锚标记吗? 您的代码

$('.menu-item-has-children a').attr('class', 'dropdown-toggle').attr('id','navbarDropdown').attr('data-toggle','dropdown').attr('aria-haspopup','true').attr('aria-expanded','false');

$('.menu-item-has-children a')更改为$('.menu-item-has-children > a')

喜欢

$('.menu-item-has-children > a').attr('class', 'dropdown-toggle').attr('id','navbarDropdown').attr('data-toggle','dropdown').attr('aria-haspopup','true').attr('aria-expanded','false');