我正在尝试一些 jQuery,但有些部分我不明白。我也很难用谷歌搜索,因为我不太确定术语 - 因此我问这个问题并将解释我的确切意图。
这是我的 HTML 标记。
<div class="contentLarge">
<a href=""><header>Use responsive design.</header></a>
<div class="contentFlex">
<div class="contentFlex1"></div>
<div class="contentFlex2"></div>
</div>
现在我想要的是,当我将鼠标悬停在 anchor 链接上时,整个 contentLarge 容器的背景都会发生变化。我的页面上有几个这样的容器。
这是 jQuery:
$(document).ready(function(){
$(".contentLarge header").mouseenter(function(){
$(".contentLarge").css({"background-color": "red"})
});
});
现在我明白了,现在当我悬停时 - 每个 contentLarge 容器都会将其背景更改为红色。这不是我想要的。
但是当我尝试使用 $(this) 选择器在此函数中进行定位时 - 更改的是 HEADER,而不是 contentLarge。像这样;
$(document).ready(function(){
$(".contentLarge header").mouseenter(function(){
$("this").css({"background-color": "red"})
});
});
我该如何编写才能使 $(this) 成为目标容器 - 仅将其背景更改为红色,而不是将所有容器或仅更改为标题。
最佳答案
使用 parent()
指向包含您悬停的链接的 .contentLarge
容器:
$(document).ready(function(){
$(".contentLarge header").mouseenter(function(){
$(this).parent().css({"background-color": "red"})
});
});
另一种选择是使用 closest()
,它会搜索与 .contentLarge
类最接近的实例。当 .header
和 .contentClass< 之间有多层时,有助于防止使用
..parent().parent().parent()...
/
$(document).ready(function(){
$(".header").mouseenter(function(){
$(this).closest('.contentLarge').css({"background-color": "red"})
});
});
关于jquery - 使用 jQuery 定位 (this) 未按预期工作,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31641799/