Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/jquery/86.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
使用jquery打开最近的容器div_Jquery_Closest - Fatal编程技术网

使用jquery打开最近的容器div

使用jquery打开最近的容器div,jquery,closest,Jquery,Closest,我有个问题。我有这个html。在readmore框中,有很多内容。我还想了解更多。在网页上阅读更多打开的链接和阅读更多框 <p> <a href="http://staging.triple-b-it.nl/requirements-management/" title="Lees verder" class="readmore-open">Lees verder</a> </p> <div class="readmore-box">

我有个问题。我有这个html。在readmore框中,有很多内容。我还想了解更多。在网页上阅读更多打开的链接和阅读更多框

<p>
<a href="http://staging.triple-b-it.nl/requirements-management/" title="Lees verder" class="readmore-open">Lees verder</a>
</p>

<div class="readmore-box">

</div>
您的DOM遍历有点错误。

.closest()
仅在DOM树中查找当前选定节点的祖先。在本例中,
.readmore box
不是祖先,因此无法找到

目前,按照您构建HTML的方式,您需要访问父级,然后查找下一个同级。您可以考虑重新配置HTML以使DOM穿越更加可靠。例如,如果元素与同级元素处于同一级别,则可以使用
.next()
查找下一个同级元素

例如,将类声明上移到containing
。您可以这样做:

HTML:

另一种方法是提供一个可以依赖的共同祖先

HTML:

第二种方法可能更灵活,因为您可以在该公共祖先中的几乎任何位置(链接之前,在与链接不同的层次级别上,等等)使用
.readmore框

$('.readmore-open').click(function(e){
    $(this).closest('.readmore-box').toggleClass('active');
})
$('.readmore-open').click(function(){
    $(this).closest('p').next('.readmore-box').toggleClass('active');
});
<p class="readmore-open">
    <a href="http://staging.triple-b-it.nl/requirements-management/" title="Lees verder">Lees verder</a>
</p>
<div class="readmore-box">...</div>
$('.readmore-open').click(function(e){
    $(this).next('.readmore-box').toggleClass('active');
})
<div class="readmore">
    <p>
        <a href="http://staging.triple-b-it.nl/requirements-management/" title="Lees verder" class="readmore-open">Lees verder</a>
    </p>
    <div class="readmore-box">...</div>
</div>
$('.readmore-open').click(function(e){
    $(this).closest('.readmore').find('.readmore-box').toggleClass('active');
})