2012-04-21 3 views
1

div内のスパンにclickイベントを追加しています。目に見えるようになるこのイベントのターゲットはdiv内にある最初のdiv、2つのdivsです。それを見つけるためにDOMをどのようにトラバースできますか?divのspan in/divからDOMをトラバースする

は、おそらくそれは、コードをより明確になります:

<div a> 
    <h2> 
     <span id="here">Click</span> 
    </h2> 
</div> 

<div></div> 

<div> 
    <div class="targetDiv">This is the div we need to find</div> 
    <div class="targetDiv">There are other divs with the same id, but we don't need to find those</div> 
    <div class="targetDiv">Not looking for this one </div> 
    <div class="targetDiv">Or this one either</div> 
</div> 

私は左と右の検索したと答えを見つけることができません。イベントをスパンの直後の最初のdivにのみ制限することは重要です。

ご協力いただければ幸いです。示されているように

+1

あなたが探しているdiv内のテキストを除いて、それ以外は何を区別していますか?彼らが掲示されており、変更することができない場合は、あなたの質問にそれを述べるべきです。あなたのページに – Lazerblade

+0

、同様の構造を含む他のdivがありますか?同じことをする他のスパンはありますか? – Joseph

答えて

0

をつかまえました。私はあなたがhtmlファイルに保存して自分でテストできる例を提供しました

<style> 
.targetDiv{display:none;} 
</style> 

<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.7.1/jquery.min.js" type="text/javascript"></script> 

<script type="text/javascript"> 
$(document).ready(function(){ 
$('#here').click(function(){ 
$('.targetDiv').first().show(); // or whatever you want 
}); 
}); 
</script> 

<div a> 
    <h2> 
     <span id="here">Click</span> 
    </h2> 
</div> 

<div></div> 

<div> 
    <div class="targetDiv">This is the div we need to find</div> 
    <div class="targetDiv">There are other divs with the same id, but we don't need to find those</div> 
    <div class="targetDiv">Not looking for this one </div> 
    <div class="targetDiv">Or this one either</div> 
</div> 
+0

本当にありがとうございました。私はセレクタがDOM内を前進する方法を知りませんでした。私が見つけることができたのは両親と最寄りの人でした。これは役に立ちます。 – navarro

2

、コードは次のようになります。魚の

$('span#here').on('click', function() { 
    $(this).closest('div').siblings(':contains(.targetDiv)').children().eq(0).show(); 
} 
1

Here's a sampleを私たちは、この作品

$(function() { 
    $('#here').on('click', function() { 
     var div = $(this)   //the element clicked 
      .closest('div')  //find nearest parent div 
      .nextAll(':eq(1)')  //find the second next div 
      .children(':eq(0)') //find the first child of it 
      .show();    //remove invisible cloak 
    }); 
});​ 
+0

私はこれを可能な代替手段と考えていました。コードをテストしましたが、機能しませんでした。私はこの方法で動作させるなら、あなたにもう一度お試しして、アップデートします。ありがとう。 – navarro

関連する問題