2014-01-10 25 views
1

如何找到其他的div元素如何找到存在於內部的div元素從jQuery的

HTML

<div> 
    <div> 
     <a class="txt">Some text</a> 
    </div> 


    <div> 
     <a class="txt">Some text</a> 
     <button id="button"/> 
    </div> 
</div> 

jQuery的

$(".button").bind("mouseover", function() { 
    $(this).siblings(".txt").text("some more text")); 
}); 

它工作正常,如果該元素存在於同一個Div中,但是如果我想要捕獲存在於不同div中的元素,那麼它不會工作(顯然)如此..任何答案如何使其工作?

+0

你需要找到的[穿越功能]的正確組合(http://api.jquery.com/category/traversing/)。在這個特定的情況下,我可能會使用像'$(this).parent()。prev()。children('.txt')' –

+1

**免責聲明:我是作者。**您可能會覺得這很有用這種情況下:http://techfoobar.com/jquery-next-in-dom/ - 在這種情況下,使用它像'$(this).prevInDOM('。txt');' – techfoobar

+0

您也可以通過以下方式解決此問題:使用類或數據屬性來識別該對。例如,如果第二個文本包含與第一個相關的一些細節,則可以使用'class =「txt details」'或'data-type =「details」'。 – Ziggy

回答

2

例子:http://jsfiddle.net/wrxsti85/Bh3Ex/

你需要找到適合您的特定情況下的具體DOM traversion方法。就像這樣:

$(this).parent().prev().find('.txt').text("some more text"); 

.parent()

.prev()

.find()

有幾個人,如.children(),但你需要找到適用於您的使用案例的人。

編輯:http://api.jquery.com/category/traversing/

希望這有助於!

+0

它的工作... http://api.jquery。com/category /遍歷/ – Faizan

+0

良好的鏈接,我不知道存在。我會將其添加到答案中。很高興它的工作。 :) – wrxsti

0

我會做到這一點,使用更maintanable方式:

jsFiddle

HTML:

<div class="container"> 
    <div> 
     <a class="txt">Some text</a> 
    </div> 
    <div> 
     <button class="button"/> 
    </div> 
</div> 

的jQuery:

$(".button").on("mouseover", function() { //or still use bind depending your jQuery version 
    $(this).closest(".container").find('.txt').text("some more text"); 
}); 
0

改變這一點:

$(this).siblings(".txt").text("some more text")); 

這樣:

$(this).closest('div').siblings('div').find('.txt').text('some more text'); 
相關問題