[英]Click event only on specific div
I've got a page with product images on it and above each image is a 'more info' button. 我的页面上有产品图片,每个图片上方是一个“更多信息”按钮。 When clicked there is an overlay over the image with more information.
单击后,图像上会出现一个叠加层,其中包含更多信息。 The html looks something like this:
html看起来像这样:
<div class=“products_overlay overlay_test”>
<div class=“products_overlay_info”>
<div class=“product_more_info”>
<span>More Info</span>
</div>
</div>
<ul class=“hover_text”>
<li class=“product_less_info”><span>Less Info</span></li>
</ul>
</div>
Now once the overlay is visible there's another button which says 'less info' and once clicked it hides the overlay with the extra information. 现在,一旦覆盖层可见,就会出现另一个按钮,上面写着“较少信息”,一旦单击,它将隐藏带有额外信息的覆盖层。 This is the jQuery for it:
这是它的jQuery:
$j('.product_more_info').on('click', function(){
$j('.product_less_info').show();
$j('.product_more_info').hide();
});
$j('.product_less_info').on('click', function(event){
event.preventDefault();
$j('.product_more_info').show();
$j('.product_less_info').hide();
});
This works, however my problem is that it's a list of products/images so when the user click 'more info' and it hides that div it hides the div for all the products/images , not just the one the user clicked on. 这有效,但是我的问题是这是产品/图像的列表,因此当用户单击“更多信息”并隐藏该div时,它会隐藏所有产品/图像的div,而不仅仅是用户单击的那个。 I've tried using
.next
but with no luck. 我试过使用
.next
但没有运气。
$j('.product_more_info').on('click', function(){
$j(this).next('.product_less_info').show();
$j(this).next('.product_more_info').hide();
});
Any ideas how to achieve this? 任何想法如何实现这一目标?
easiest way to do it is to access common ancestor using .closest(selector)
- in this case it is .products_overlay
最简单的方法是使用
.closest(selector)
访问共同祖先-在这种情况下为.products_overlay
$j('.product_more_info').on('click', function(){
$j(this).closest('.products_overlay').find('.product_less_info').show();
$j(this).hide();
});
you can also achieve this calling .parent()
two times: 您也可以两次实现此调用
.parent()
:
$j('.product_more_info').on('click', function(){
$j(this).parent().parent().find('.product_less_info').show();
$j(this).hide();
});
but .closest(selector)
in this case is more reliable as you may change your html structure in the future a bit 但是
.closest(selector)
在这种情况下更可靠,因为您将来可能会更改html结构
Try this 尝试这个
$j('.product_more_info').on('click', function(){
$j('.product_less_info', $j(this).parents('.products_overlay')).show();
$j(this).hide();
});
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.