使用jquery选择元素附近的第一个h2
Select the first h2 near a element with jquery
我真的是JS和JQuery的新手,我选择动画元素失败了,这是我的HTML
<div class="box-product">
<h2>Light</h2>
<figure>
<img src="img/boxes/light.jpg" alt="Pepper Box Light" title="Pepper Box Light" />
<figcaption>
Versão light, porém igualmente apimentada da nossa PepperBox, para quem quer se divertir com seu amor</figcaption>
</figure>
</div><!-- box-product -->
当用户悬停在figure
上时,我试图选择h2
,所以这是我的最佳猜测:
$('.box-product figure').hover(function() {
$('.box-product').closest('h2').animate({color: 'f00'}, 'slow')
}, function() {
$('.box-product').closest('h2').animate({color: 'inherit'}, 'slow')
});
但是什么都没发生,所以,我需要一些帮助。
谢谢!
closest():
获取与选择器匹配的第一个元素,从当前元素开始,向上遍历DOM树。
您可以使用prev()
方法:
$('.box-product figure').hover(function() {
$(this).prev().animate({color: '#f00'}, 'slow')
}, function() {
$(this).prev().animate({color: 'inherit'}, 'slow')
});
或:
$('.box-product figure').hover(function() {
$(this).siblings('h2').animate({color: '#f00'}, 'slow')
}, function() {
$(this).siblings('h2').animate({color: 'inherit'}, 'slow')
});
使用.prev()
,因为所需的h2
是figure
的前一个同级,.closest()
会搜索所选项目的祖先以查找匹配项。
$('.box-product figure').hover(function() {
$h2 = $(this).prev('h2');
$h2.animate({color: '#f00'}, 'slow')
}, function() {
$h2.animate({color: '#000'}, 'slow')
});
FIDDLE
closest()
返回dom树中父节点中的元素。您将需要siblings("h2")
或仅需要prev()
来获得悬停的<figure>
:之前的元素
$('.box-product figure').hover(function() {
$(this).prev().animate({color: 'f00'}, 'slow')
}, function() {
$(this).prev().animate({color: 'inherit'}, 'slow')
});
从选择器$('.box-product')
开始,您可以使用find("h2")
或children("h2")
,但这将选择整个文档中的所有内容。如果你的盒子是独一无二的,你也可以使用类似$("#box-product h2")
的东西。
h2
是figure
的兄弟。
$('.box-product figure').hover(function() {
$(this).siblings('h2').animate({color: '#f00'}, 'slow')
}, function() {
$(this).siblings('h2').animate({color: 'inherit'}, 'slow')
});
试试这个。。。最近的第一个元素。。。
$('h2').siblings(':first');
Fiddle
closest()方法从父层次结构中查找最接近的匹配,而不是从子元素或同级元素中查找。
在您的情况下,您只需要从父元素中查找子元素。像这样:
$('.box-product figure').hover(function() {
$(this).closest('.box-product').find('h2').animate({color: 'f00'}, 'slow')
}, function() {
$(this).closest('.box-product').find('h2').animate({color: 'inherit'}, 'slow')
});
相关文章:
- 而循环只设置php中输入字段中的第一个值
- 错误:$injector:modulerr模块错误(我的第一个SPA应用程序)
- IE11中的第二个调用取消了第一个Fetch API调用
- Javascript XMLHttpRequest——只有第一个POST请求有效
- 使用javascript或angularjs特定过滤器搜索字符串中第一个img标记的json值
- 将OnClick函数设置为<ul>,最后一个ul是擦除第一个ul-s
- RxJS油门行为;立即获取第一个值
- Angular UI网格:如何通过第一个UI网格中的按钮使第二个UI网格可见
- 选择多个实例中的第一个
- 如何在调用下一个请求之前完成第一个Ajax Get请求
- Lodash:返回对象的第一个键,该对象的值(即数组)中有一个给定的元素(即字符串)
- 看起来第一个console.log是'It’不太对
- 与杜兰达尔合作的第一个JavaScript项目.尝试从第三方 API 获取数据
- 节点发布错误对象的第一个“属性”
- Javascript:表单验证getElementById仅返回第一个id元素
- 仅将 CSS 规则应用于
中的第一个 ,而不分配类/ID - JS在隐藏未定义的值后仅从数组中返回第一个id的值
- 使用jquery选择元素附近的第一个h2
- 仅在第一个li内查找h2
- jQuery [object object]在尝试将第一个h2标签转换为h1时出现错误