gpt4 book ai didi

Jquery 在 prev 中选择子项不起作用

转载 作者:行者123 更新时间:2023-12-01 06:32:22 25 4
gpt4 key购买 nike

代码:

  <article>
<a href="#"><h4>h4 inside anchor</h4></a>
<p>This is a sibling paragraph of that anchor which had h4 in it</p>
</article>
<script>
$('article p').click(function(){
$(this).prev('a h4').css("background-color", "yellow");
});
</script>

当我点击该段落时,我希望 h4 的背景颜色为黄色,但它不起作用。

此外,关于“prev”的 JQuery 文档对于 prev 内带有后代的选择器也不太清楚(因此第一个含义是它与选择器的常见预期行为没有什么不同):

If a selector is provided, it retrieves the previous sibling only if it matches that selector.

那么到底出了什么问题呢?

最佳答案

问题是因为您在 prev() 调用中使用了子选择器。 jQuery 内部使用类似于 is() 的逻辑来确定同级元素是否与此选择器匹配,因此它将测试 a is 是否为 h4,但事实绝不会如此。

要解决此问题,请结合使用 prev()find():

$('article p').click(function() {
$(this).prev('a').find('h4').addClass('highlight');
});
.highlight { background-color: #FF0; }
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<article>
<a href="#">
<h4>h4 inside anchor</h4>
</a>
<p>This is a sibling paragraph of that anchor which had h4 in it</p>
</article>

关于Jquery 在 prev 中选择子项不起作用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/60736517/

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