单击加号图标时,我希望仅针对该特定 div 中的一加图标显示复选图标。整个页面中并非所有加号图标。这是 html,后面是 jQuery。
<div class="pin">
<img class="brand-logo" src="img/nike.jpg" />
<div class= "hover-popup">
<h1 class="brand-name">Nike</h1>
<img class="plus-icon" src="img/plus-icon.png" />
<img class="check-icon" src="img/check-icon.png" />
</div>
</div>
<div class="pin">
<img class="brand-logo" src="img/calvinklein.jpg" />
<div class= "hover-popup">
<h1 class="brand-name">Calvin Klein</h1>
<img class="plus-icon" src="img/plus-icon.png" />
<img class="check-icon" src="img/check-icon.png" />
</div>
jQuery
$(".plus-icon").click(
function () { $(this).find('.check-icon').show(); },
function () { $(this).find('.plus-icon').hide(); }
);
$(".check-icon").click(function() {
function () { $(this).find('.plus-icon').show(); },
function () { $(this).find('.check-icon').hide(); }
);
首先找到包含的div,因为它的祖先是
.check-icon,.plus-icon
,所以使用.closest()
,那么你可以使用find()
$(this).closest('.hover-popup').find('.check-icon').show();
siblings
选择器。
$(".plus-icon").click(
function () { $(this).siblings('.check-icon').show(); },
function () { $(this).hide(); }
);
$(".check-icon").click(function() {
function () { $(this).siblings('.plus-icon').show(); },
function () { $(this).hide(); }
);
鉴于您的示例 HTML,这将是首选解决方案。
.parent
,然后使用 find
从那里下降。
$(".plus-icon").click(
function () { $(this).parent().find('.check-icon').show(); },
function () { $(this).parent().find('.plus-icon').hide(); }
);
$(".check-icon").click(function() {
function () { $(this).parent().find('.plus-icon').show(); },
function () { $(this).parent().find('.check-icon').hide(); }
);
最后,如果您不确定
.hover-popup
元素相对于按钮的位置,请使用 .closest
找到它,然后从那里下降。
$(".plus-icon").click(
function () { $(this).closest('.hover-popup').find('.check-icon').show(); },
function () { $(this).closest('.hover-popup').find('.plus-icon').hide(); }
);
$(".check-icon").click(function() {
function () { $(this).closest('.hover-popup').find('.plus-icon').show(); },
function () { $(this).closest('.hover-popup').find('.check-icon').hide(); }
);
使用 Jquery 你的代码将如下所示:
$(document).ready(function(){
$('.plus-icon').click(function(){
$(this).hide();
$(this).siblings('.check-icon').show()
})
$('.check-icon').click(function(){
$(this).hide();
$(this).siblings('.plus-icon').show()
})
})
试试这个
$(".plus-icon").click(
function () { $(this).next('.check-icon').show(); },
function () { $(this).hide(); }
);
$(".check-icon").click(function() {
function () { $(this).prev('.plus-icon').show(); },
function () { $(this).hide(); }
);
可能最简单的方法是使用 .siblings() 函数。
例如
$('.plus-icon').click(function(){
$(this).siblings('.check-icon').show();
});