遍历跨越div的跨越DOM

时间:2012-04-21 02:49:32

标签: javascript jquery jquery-selectors traversal

我将点击事件添加到div中的范围内。这个事件的目标,将变得可见,是一个div内的第一个div,两个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非常重要。

非常感谢任何帮助。

3 个答案:

答案 0 :(得分:2)

如图所示,代码如下所示:

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

答案 1 :(得分: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
    });
});​

答案 2 :(得分: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>