jQuery隐藏/显示特定的div元素
这是我的html代码jQuery隐藏/显示特定的div元素,jquery,Jquery,这是我的html代码 <div class="w-grid-list"> <article class="w-grid-item"> <div class="w-grid-item-h"> <div class="w-vwrapper"> <div class="w-post-elm"> <img width="350" height="233" sr
<div class="w-grid-list">
<article class="w-grid-item">
<div class="w-grid-item-h">
<div class="w-vwrapper">
<div class="w-post-elm">
<img width="350" height="233" src="#" sizes="350px">
</div>
<div class="product_details" style="display: none;">
<div class="w-post-elm post_content usg_post_content_1">
<p class="prod_text desktop_prod_text" style="display: block;">Солодкі млинці з яблучним варенням.<br>
<strong>200 г 714 ккал</strong>
</p>
</div>
</div>
<h2 class="product_title">Млинці з сиром та курагою</h2>
<div class="w-hwrapper">
<div class="w-post-elm">
<span class="w-post-elm-before">Weight: </span>
<span class="woocommerce-product-attributes-item__value">200 g</span>
</div>
</div>
</div>
</div>
</article>
<article class="w-grid-item">
<div class="w-grid-item-h">
<div class="w-vwrapper">
<div class="w-post-elm">
<img width="350" height="233" src="#" sizes="350px">
</div>
<div class="product_details" style="display: none;">
<div class="w-post-elm post_content usg_post_content_1">
<p class="prod_text desktop_prod_text" style="display: block;">Солодкі млинці з яблучним варенням.<br>
<strong>200 г 714 ккал</strong>
</p>
</div>
</div>
<h2 class="product_title">Млинці з сиром та курагою</h2>
<div class="w-hwrapper">
<div class="w-post-elm">
<span class="w-post-elm-before">Weight: </span>
<span class="woocommerce-product-attributes-item__value">200 g</span>
</div>
</div>
</div>
</div>
</article>
</div>
但此代码工作不正常您可以使用以下方法:
$('.product_title').click(function(){
$(this).prev('.product_details').hide();
})
使用
$(this)
我们只针对当前单击的product\u title
元素之前的product\u details
div。要针对的元素是触发单击事件的元素的同级,因此可以使用.sibles()方法选择上一个元素,或者也可以将dom移动到父元素(项目),然后通过.find()方法选择要作为目标的元素:
非常感谢。这是我的工作。但是可以再次单击H2标记添加show()?您只需使用
toggle()
而不是hide()
。如果有帮助,请告诉我@塔普拉更新。
$('.product_title').click(function(){
$(this).prev('.product_details').hide();
})
$(".product-title").on('click', function () {
$(this).siblings('.product-details').hide('fast');
});
// OR
$(".product-title").on('click', function () {
$(this).closest('article').find('.product-details').hide('fast');
});