2012-03-15 55 views
1

我正在嘗試遍歷DOM到最近的DIV。下面的標記如下。jQuery nearest(),parents()和parent()會影響同一DOM級別的多個元素

<div> 
    <span> 
      <a class="anchor">Text</a> 
    </span> 
</div> 
<div> 
    <span> 
      <a class="anchor">Text</a> 
    </span> 
</div> 
<div> 
    <span> 
      <a class="anchor">Text</a> 
    </span> 
</div> 

當我使用以下任一:

$('.anchor').closest('div').css('background-color', 'red'); 
$('.anchor').parents('div').css('background-color', 'red'); 
$('.anchor').parent().parent().css('background-color', 'red'); 

它會影響所有像這樣的DIV:

<div style="background-color: red"> 
    <span> 
      <a class="anchor">Text</a> 
    </span> 
</div> 
<div style="background-color: red"> 
    <span> 
      <a class="anchor">Text</a> 
    </span> 
</div> 
<div style="background-color: red"> 
    <span> 
      <a class="anchor">Text</a> 
    </span> 
</div> 

如果我點擊中央錨件我想這一點:

<div> 
    <span> 
      <a class="anchor">Text</a> 
    </span> 
</div> 
<div style="background-color: red"> 
    <span> 
      <a class="anchor">Text</a> 
    </span> 
</div> 
<div> 
    <span> 
      <a class="anchor">Text</a> 
    </span> 
</div> 

我想我明白了爲什麼closest()將匹配所有三個DIV作爲最接近點擊錨點的DIV,因爲它一般匹配DIV。

但是,當使用parents()parent()它不像其他DIV不是一個點擊錨的父親那樣清晰。但是我也可以看到它可能只是在DOM中的這個級別再次匹配DIV。儘管看起來像parents()parent()應該在匹配時保持更多的上下文上下文。

+0

你能證明你的點擊事件? – 2012-03-15 18:37:37

回答

7

如果指定$(".anchor"),它是尋找所有在你的頁面的.anchor選擇,然後一個接一個,這樣做對他們每個人的.closest('div').css('background-color', 'red')匹配的對象。如果你想瞧一瞧它僅被點擊的對象的父DIV,你需要使用點擊式對象爲出發點,爲您.closest('div')電話這樣的:

$(this).closest('div').css('background-color', 'red'); 

這便只會影響點擊從this對象開始父DIV。

你點擊處理器您還沒有顯示的代碼,但它可能是這樣的:

$(".anchor").click(function() { 
    $(this).closest('div').css('background-color', 'red'); 
}); 

或者,如果你想清楚可能已經紅從以前的點擊,然後其他項目使之成爲一件紅色的,你可以這樣做:

$(".anchor").click(function() { 
    var master$ = $(this).closest('div') 
    master$.siblings().css('background-color', 'white'); 
    master$.css('background-color', 'red'); 
}); 
+0

我覺得'.css('background-color','inherit')'會更合適。 – 2012-03-15 18:42:50

+0

啊,是的,愚蠢的我,忽略了最簡單明顯的問題。我將所有錨與類錨相匹配並向上移動。因爲他們都有班級主播,他們都會匹配。我想,有時間休息一下。謝謝! – hungerstar 2012-03-15 18:43:02

+0

@JamesAylett - 我只是用一個例子。在設置爲紅色之前,我們不知道它是什麼顏色。也許以前是白色的。這只是一個例子,向他們展示如何去做。 – jfriend00 2012-03-15 18:45:17

2

您最初的節點查詢$('.anchor')是匹配所有三個<a>元素,讓你從那麼做的一切(是它closestparents還是什麼永遠)會爲每個匹配元素髮生一次。如果你使用任何一個單擊處理這些方法的,也不會造成問題,因爲它會只發射了一個元素。

您可能會更好地添加/刪除類,因爲這比整理您直接使用.css()添加的CSS更容易一些。

+0

確實如此,無論出於何種原因,這正是我在示例中使用的原因。實際的標記還有更多的事情要做,而不僅僅是改變背景顏色。 – hungerstar 2012-03-15 19:03:11

1

$('.anchor').closest('div')會發現所有的.anchor元素,並找到與其最接近的股利和應用背景色爲所有的人。

您應該使用this指被點擊的點擊處理程序中的元素。

$(this).closest('div').. 

試試這個。

$(".anchor").click(function() { 
    $(this).closest('div').css('background-color', 'red'); 
}); 
1

您可以嘗試

$(this).closest('div').css('background-color', 'red'); 
$(this).parents('div').css('background-color', 'red'); 
$(this).parent().parent().css('background-color', 'red'); 

希望這有助於... :)

相關問題