2012-04-10 35 views
4
<tr> 
    <th scope="row"> 
     <span id="home_location_indicator">(Home)</span> 
    </th> 
    <td> 
     <span class="postal_code_display">...</span> 
    </td> 
    <td><input value="1" name="location_select" type="radio" /></td> 
</tr> 

說,我有一個<table>包含一對夫婦<tr>就像上面的一個。在<tr>'s中,只有一個有<span id="home_location_indicator">(Home)</span>有什麼更好的方法到達另一個具有公共祖父母作爲當前節點的節點?

我想對方法決定採取檢索屬於<tr><span id="home_location_indicator">輸入name="location_select"

這裏有兩種方法我能想到的:

  1. $("tr").has("#home_location_indicator").find('input[name="location_select"]').val()
  2. $("#home_location_indicator").parents("tr").find('input[name="location_select"]').val()

哪一個是一個更好的辦法?爲什麼?或者它甚至很重要?

回答

2

最好的方法是使用.closest()而不是.parents(),因爲一旦找到匹配就會停止遍歷。

$("#home_location_indicator") // ID, very fast 
    .closest("tr") // Upwards traversal, fast, stops at tr 
    .find(':radio[name="location_select"]').val() // Find, slow-ish 

這比自上而下的辦法要好得多:

$("tr") // getElementsByTagName, very fast 
    .has("#home_location_indicator") // traverse EVERY tr ALL the way down, very slow! 
    .find('input[name="location_select"]').val() // Find, slow-ish 
+2

是......'.closest'比'.parents'更好http://jsperf.com/closest-vs-parents – 2012-04-10 19:20:00

2

你的第二個方法是好多了,因爲這將縮小穿越從ID開始,並從那裏穿過。與你有什麼小的修改,請參閱下文,

編輯:使用.closest優於.parents - >Proof

$("#home_location_indicator") 
    .closest("tr") 
    .find(':radio[name="location_select"]').val() 

在你的第一個方法沒有多大意義,因爲你正在尋找一個ID的.has("#home_location_indicator")。如果你想得到一個ID使用$('#IDSelector')這是最快的選擇,因爲它在內部使用document.getElementByID('IDSelector')

+0

感謝增加的證明。非常感激。 – tamakisquare 2012-04-10 20:25:01

+1

給所有下流者 - >如果您不滿意並回答,請留下一個理由。 – 2012-04-10 20:34:51

+0

同意@SKS。毫無理由的下調讓人們感到困惑,並且無助於建設一個建設性的社區。 – tamakisquare 2012-04-10 21:04:11

相關問題