2012-04-21 165 views
1

我将点击事件添加到div内的跨度。这个事件的目标将变得可见,是第一个div,在div内,两个div。我如何遍历DOM来找到它?从跨度/跨度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 2012-04-21 02:52:49

+0

在您的网页中,是否有其他divs包含类似的结构?还有其他跨度是否也做同样的事情? – Joseph 2012-04-21 02:54:11

回答

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 2012-04-21 04:16:13

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 2012-04-21 04:17:16