我有一个这样的div:
<div class="country">
<div class="cty_popover">
<p>TITLE</p>
<ul>
<li>NAME 1</li>
<li>NAME 2</li>
</ul>
</div>
<img src="resources/images/map-marker.png" alt=" ">
</div>和这个jQuery:
$(document).ready(function(){
$('.country img').hover(function() {
$(this).parents('.cty_popover').fadeIn(800);
},
function() {
$('.cty_popover').fadeOut(300);
});
});我知道jQuery中的这一行是错误的:
$(this).find('.cty_popover').fadeIn(800);我需要针对以下目标:
.cty_popover 在函数中:
$('.country img').hover所以基本上我的问题是:
如何使用$(this)以.cty_popover为目标?我需要从'img‘升级到目标,但不确定怎么做?
我有很多这样的.cty_popover div,这就是为什么我想使用$(this),所以我不会针对所有的div。
有没有人知道为什么我不能让它工作?
谢谢
发布于 2017-01-12 01:43:55
由于img是cty_popover的兄弟,您可以使用prev()函数将其作为目标-请参阅下面的演示:
$(document).ready(function() {
// hide all `cty_popover` sections initially
$('.cty_popover').hide();
// hover listener
$('.country img').hover(function() {
$(this).prev('.cty_popover').fadeIn(800);
}, function() {
$(this).prev('.cty_popover').fadeOut(300);
});
});<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="country">
<div class="cty_popover">
<p>TITLE</p>
<ul>
<li>NAME 1</li>
<li>NAME 2</li>
</ul>
</div>
<img src="http://placehold.it/200x200">
</div>
发布于 2017-01-12 01:46:55
由于img节点是cty_popover节点的同级节点,因此请替换此行
$(this).parents('.cty_popover').fadeIn(800);这样应该行得通。
$(this).siblings('.cty_popover').fadeIn(800);Here's示例
发布于 2017-01-12 02:04:48
您应该使用同级:https://api.jquery.com/siblings/
请看这个处理HTML的示例:
$(document).ready(function(){
$('.country').children('img').hover(function() {
$(this).siblings( '.cty_popover').fadeIn(800);
},
function() {
$('.cty_popover').fadeOut(300);
});
});.country {
position. relative;
width: 300px;
}
.country > img {
width: 100%;
display: block;
}
.country .cty_popover {
display: none;
position: absolute;
left: 10px;
top: 10px;
background: rgba(255,255,0,.9);
padding: 5px;
border-radius: 5px;
width: 285px;
}
.country .cty_popover:after {
content: "";
width: 0;
height: 0;
border-left: 20px solid transparent;
border-right: 20px solid transparent;
border-top: 20px solid rgba(255,255,0,.9);
position: absolute;
bottom: -20px;
left: 50%;
margin-left: -10px;
}<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<div class="country">
<div class="cty_popover">
<p>TITLE</p>
<ul>
<li>NAME 1</li>
<li>NAME 2</li>
</ul>
</div>
<img src="https://placeimg.com/300/200/tech" alt=" ">
</div>
https://stackoverflow.com/questions/41597255
复制相似问题