代码之家  ›  专栏  ›  技术社区  ›  aiternal

如何使用Jquery将类添加到触发器的上部元素?

  •  0
  • aiternal  · 技术社区  · 16 年前

    我在做一个Jquery手风琴的东西。我想向包含accordion触发器的div添加一个类<a>标签。你可以看看我的密码。我想添加“第一”类名只是第一个“新闻”类时,点击“衰退时尚在日本视频”标题。

            <!-- news items starts-->
            <div class="newsitems">
              <h3 class="business"> <a href="#" title="expand"><img src="images/expand_icon.gif" alt="collapse" class="collpase" /> Recession fashion in Japan Video</a> </h3>
              <p class="timestamp">0100hrs</p>
            </div>
            <!-- news items ends-->
            <!-- news items starts-->
            <div class="newsitems">
              <h3 class="sports"> <a href="#" title="expand"><img src="images/expand_icon.gif" alt="collapse" class="collpase" /> Murray survives five-set thriller at Wimbledon</a> </h3>
              <p class="timestamp">0100hrs</p>
            </div>
            <!-- news items ends-->
    
    4 回复  |  直到 16 年前
        1
  •  2
  •   SLaks    16 年前

    你在找 closest 方法,whch查找包含元素的最内部父级。

    例如:

    $('div.newsItems h3 a').click(function() { 
        $(this).closest('div.newsItems').addClass('first');
    });
    
        2
  •  0
  •   Dustin Laine    16 年前
    $('div.newsitems h3 a').click(function() {
        $(this).parent().parent().addClass('first');
    });
    
        3
  •  0
  •   aiternal    16 年前

    var dropDown = $(this).parent().next().next(); /* This is configured for my script. Yours may be different*/
    $('div.newsitems').not(dropDown).removeClass('first');
    
        4
  •  0
  •   Mark    16 年前

    只是为了另一个答案。

    $('div.newsItems').click(function(e){
        if($(e.target).is("IMG")){
            $(this).addClass("first");
        }
    }
    

    编辑: 更改了 if($(e.target).is("a")){ IMG 斯莱克斯指出我错过了那个标签。