我正在尝试创建一个动态生成以下代码的站点。它有多个 div.container 及其子实例。问题是,当我单击缩略图 (.color-thumbs img) 时,它还会触发所有图像 (.imgWrapper img) 的更改。我需要做的是为缩略图创建一个唯一的触发器,它只会影响同一容器内的图像。
这是我的代码:
$('.color-thumbs img').click(function() {
var thmb = this;
var src = this.src;
$('.color-thumbs img').parent('.imgWrapper').append('crayz');
$('.imgWrapper img').fadeOut(400,function(){
thmb.src = this.src;
$(this).fadeIn(400)[0].src = src;
});
});
.color-thumbs img{
margin-right:3px;
margin-top:3px;
width:30px;
height: 30px;
float:left;
box-sizing: border-box;
}
.container {
clear: both;
margin-bottom: 4em;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="container">
<div class="imgWrapper">
<img src="http://placehold.it/300x160/cf5" />
</div>
<div class="color-thumbs">
<img src="http://placehold.it/300x160/444" />
<img src="http://placehold.it/300x160/f1f" />
</div>
</div>
<div class="container">
<div class="imgWrapper">
<img src="http://placehold.it/300x160/cf5" />
</div>
<div class="color-thumbs">
<img src="http://placehold.it/300x160/444" />
<img src="http://placehold.it/300x160/f1f" />
</div>
</div>
提前致谢!
最佳答案
您可以使用 .closest()细化被点击的 img
所属的 container
元素,然后使用 .find() 在其中查找目标 .imgWrapper img
元素,例如
$('.color-thumbs img').click(function() {
var thmb = this;
var src = this.src;
$(this).closest('.container').find('.imgWrapper img').stop().fadeOut(400, function() {
$(this).fadeIn(400)[0].src = src;
});
});
.color-thumbs img {
margin-right: 3px;
margin-top: 3px;
width: 30px;
height: 30px;
float: left;
box-sizing: border-box;
}
.container {
clear: both;
margin-bottom: 4em;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="container">
<div class="imgWrapper">
<img src="http://placehold.it/300x160/cf5" />
</div>
<div class="color-thumbs">
<img src="http://placehold.it/300x160/444" />
<img src="http://placehold.it/300x160/f1f" />
</div>
</div>
<div class="container">
<div class="imgWrapper">
<img src="http://placehold.it/300x160/cf5" />
</div>
<div class="color-thumbs">
<img src="http://placehold.it/300x160/444" />
<img src="http://placehold.it/300x160/f1f" />
</div>
</div>
关于javascript - 如何使用 jQuery 触发同一容器内的元素,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31397331/