2016-11-26 89 views
0

我正在學習jquery,我有選擇器這個小問題。jQuery上一級和.find()

這是我的DOM結構:

<li> 
    <header class="title"> 
    <span>Text</span> 
    <a href="#work-1">My trigger</a> 
    </header> 
    <div id="work-1"> 
    <div class="description"> 
     <p>some shit about the work</p> 
    </div> 
    <div class="carousel"> 
     <img/> 
     <img/> 
     <img/> 
     ... 
    </div> 
    </div> 
</li> 

確定。它是一個簡單的列表,與我的作品有很多聯繫。每個項目都有其描述和一些照片,在旋轉木馬上進行。

當我點擊鏈接,我想在jquery中創建一個變量來獲得傳送帶。我寫這個,但它不工作:

$('a').click(function(e){ 
    var href = $(e.target).attr('href'); 
    // this is to make my div#work toggle from display:none to block. 

    var carousel = $(href).find('.carousel'); 
    // this is the wrong code. I cant reach the carousel from there. 
}); 

感謝您的幫助!

+0

使用'parent()'去1級別 –

+0

我試過你的代碼,它的工作原理。你的方式也可以說比這裏的答案更好,所以我會堅持下去。你確定你的例子中的HTML與你的頁面結構相匹配嗎? – dlsso

回答

1

這應該工作:

$('a').click(function(e){ 
    var carousel = this.parents('li').find('.carousel'); 
}); 

裏面點擊處理程序, 「這」 指的是被點擊了A-元素。找到被單擊的A元素的父元素的LI元素,然後搜索作爲該LI元素的子元素的傳送帶。

0

用這個代替,旋轉木馬的一個diferent元素

$('.carousel') 
+0

我在頁面中有很多.carousel ..我必須選擇鏈接的「li」中的那個,我點擊... – mdash

0

你要回去(用.parent())兩次或使用.parents直到它找到李標籤。

$('a').click(function(){ 
 
    var href = $(this).attr('href'), 
 
    \t \t li = $(this).parents('li'), 
 
    \t \t carousel = li.find(href).find('.carousel'); 
 
    console.log(carousel); 
 
    carousel.css('background-color', 'red'); 
 
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> 
 
<ul> 
 

 
<li> 
 
    <header class="title"> 
 
    <span>Text</span> 
 
    <a href="#work-1">My trigger</a> 
 
    </header> 
 
    <div id="work-1"> 
 
    <div class="description"> 
 
     <p>some shit about the work</p> 
 
    </div> 
 
    <div class="carousel"> 
 
     <img/> 
 
     <img/> 
 
     <img/> 
 
    </div> 
 
    </div> 
 
</li> 
 
</ul>

順便說一下,你的腳本對我的作品還有:
https://jsfiddle.net/rozgwq8e/

但你可以使用$(本),而不是e.target。