使用parent()函数添加额外的属性

时间:2017-06-09 11:57:29

标签: jquery parent

我正在尝试使用attr函数根据类名添加parent()

我的代码如下:

<div class="kiwi-topbar-nav">
    <div class="uk-container">

    <nav class="uk-navbar-container uk-navbar">
        <ul>
            <li><a class="uk-navbar-toggle uk-search-icon" href="#">toggle</a></li>
            <li>...</li>        
        </ul>
    </nav>

    </div>
</div>

<div class="kiwi-main-nav">
    <div class="uk-container">

    <nav class="uk-navbar-container uk-navbar">
        <ul>
            <li><a class="uk-navbar-toggle uk-search-icon" href="#">toggle</a></li>
            <li>...</li>        
        </ul>
    </nav>

    </div>
</div>  

Jquery的:

$('.uk-navbar-container.uk-navbar').each(function() {

   $toggle = $('.uk-navbar-toggle.uk-search-icon');

  if ( $(this).parent('.kiwi-topbar-nav') ) { 
     $toggle.attr('target', '.kiwi-topbar-nav');
  } else if ( $(this).parent('.kiwi-main-nav') ) {
     $toggle.attr('target', '.kiwi-main-nav');
  } 

});

我注意到了attr。 target="kiwi-topbar-nav"kiwi-topbar-nav内添加了kiwi-main-nav div。虽然取决于父div名称,但它应具有不同的属性。我误解了parent()功能吗?如果我是,我应该使用哪个其他jquery函数?

1 个答案:

答案 0 :(得分:2)

您的$toggle是两个类的所有元素,您需要将其更改为与每个循环中当前元素相关的元素:

$('.uk-navbar-container.uk-navbar').each(function() {

   $toggle = $(this).find('.uk-navbar-toggle.uk-search-icon'); // change this line

  if ( $(this).closest('.kiwi-topbar-nav').length ) {     // change this to closest (as parent means direct parent - your div is a grandparent) and check against the length to see if it exists
     $toggle.attr('target', '.kiwi-topbar-nav');
  } else if ( $(this).closest('.kiwi-main-nav').length ) {
     $toggle.attr('target', '.kiwi-main-nav');
  } 

});

或者您可以使用函数来设置attr:

$('.uk-navbar-toggle.uk-search-icon').attr('target', function() {
    if ($(this).closest('.kiwi-topbar-nav').length) {  // check if there is a kiwi-topbar-nav 
       return '.kiwi-topbar-nav';                      // returning this sets the target attribute to this value
    } else if ($(this).closest('.kiwi-main-nav').length) {
       return '.kiwi-main-navv';
    }
});