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> 

私は<tr>のように上記のような<table>を持っています。 <tr>のうち、<span id="home_location_indicator">(Home)</span>を持つものは1つだけです。現在のノードとして共通の祖父母を持つ別のノードに到達するためのよりよいアプローチは何ですか?

私は<span id="home_location_indicator">を含む<tr>に属し入力name="location_select"を取得するために取ることのアプローチを決定しようとしています。 1がより良いアプローチです

  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つの方法がありますか?なぜ?それとも問題なの?

答えて

2

.parents()の代わりに.closest()を使用するのが最善の方法です。これは、一度一致するとトラバースを停止するためです。

$("#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 –

2

あなたの第二のアプローチは、それがIDから始まるトラバースを絞り込むと、そこからトラバースと同じように多くの良いです..あなたが持っているものの少しの変更では、以下を参照してください、

編集:.closestを使用すると、.parentsよりも優れています - >Proof

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

あなたがIDを探しているので、あまり意味がありません、あなたの最初のアプローチで.has("#home_location_indicator")。あなたがIDを取得したい場合は、内部でdocument.getElementByID('IDSelector')を使用するので、最も速いセレクタである$('#IDSelector')を使用してください。

+0

感謝。とても有難い。 – tamakisquare

+1

すべてのDownvotersに - >あなたがdownvoteと答えた場合は理由を残してください。 –

+0

@SKSと同意します。理由なしでダウン投票すると、人々は困惑し、建設的なコミュニティを構築するのに役立ちません。 – tamakisquare

関連する問題