gpt4 book ai didi

javascript - 在相同(或不同)级别上按类选择最近的元素

转载 作者:太空狗 更新时间:2023-10-29 15:49:44 25 4
gpt4 key购买 nike

如何选择具有可能与可点击元素不在同一级别的特定最近元素?

例如,假设这是输出:

<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<div>
<div>
<p class="change-on-click">A</p>
<p class="click">Click on this will change A</p>
</div>
</div>

<div>
<div>
<p class="change-on-click">B</p>
<div>
<p class="click">Click on this will change B</p>
</div>
</div>
</div>

<div>
<div>
<p class="change-on-click">C</p>
<div>
<div>
<p class="click">Click on this will change C</p>
</div>
</div>
</div>
</div>

<div>
<div>
<div>
<div>
<p class="click">Click on this will change D</p>
</div>
<p class="change-on-click">D</p>
</div>
</div>
</div>

<div>
<div>
<div>
<div>
<p class="click">Click on this will change E</p>
</div>
</div>
</div>
<p class="change-on-click">E</p>
</div>

我希望当我点击 p.click 时它会找到最近的 p.change-on-click 元素。


就是这样,可惜我不能改变HTML

$('.click').on('click', function(){
$(this).closest('.parent').find('.change-on-click').css('color', 'red');
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<div class="parent">
<div>
<p class="change-on-click">A</p>
<p class="click">Click on this will change A</p>
</div>
</div>

<div class="parent">
<div>
<p class="change-on-click">B</p>
<div>
<p class="click">Click on this will change B</p>
</div>
</div>
</div>

<div class="parent">
<div>
<p class="change-on-click">C</p>
<div>
<div>
<p class="click">Click on this will change C</p>
</div>
</div>
</div>
</div>

<div class="parent">
<div>
<div>
<div>
<p class="click">Click on this will change D</p>
</div>
<p class="change-on-click">D</p>
</div>
</div>
</div>

<div class="parent">
<div>
<div>
<div>
<p class="click">Click on this will change E</p>
</div>
</div>
</div>
<p class="change-on-click">E</p>
</div>

Here's a fiddle with the second situation

最佳答案

这将需要一种自定义方法,因为 jQuery API 不支持那种类型的搜索。基本上,只需遍历父节点,直到找到单击更改元素。

$('.click').click(function(){
var node = this;
while(node != document.body){
var target = $(node).find('.change-on-click')
if( target.length == 0 ){
node = node.parentNode;
}else{
target.css('color','red');
return;
}
}
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<div>
<div>
<p class="change-on-click">A</p>
<p class="click">Click on this will change A</p>
</div>
</div>

<div>
<div>
<p class="change-on-click">B</p>
<div>
<p class="click">Click on this will change B</p>
</div>
</div>
</div>

<div>
<div>
<p class="change-on-click">C</p>
<div>
<div>
<p class="click">Click on this will change C</p>
</div>
</div>
</div>
</div>

关于javascript - 在相同(或不同)级别上按类选择最近的元素,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/27367668/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com