我有两个带有div类的.image__content,在其中,我有一些具有唯一ids的图像。我需要隐藏所有的图像,并且只从每个.image__content显示一个图像,此时您可以看到所有的图像。
下面的代码用于获取它所做的每个.image__content,然后为每个.image__content单独运行代码,从select选项中获取当前的图像id,并使用相同的id查找图像,并显示该图像并隐藏其余的图像。
然而,目前它只适用于最后一个.image__content,所以它完全符合我的要求,但只对第二个.image__content和第一个div,它隐藏了所有的图像,甚至没有显示一个。
那么,我如何能够运行该函数并使其对两个.image__content都是可行的呢?
<div class="image__content">
<div class="images">
<img class="image image-1">
<img class="image image-2">
<img class="image image-3">
</div>
<form>
<select class="image__select">
<option value="1">Image 1</option>
<option value="2">Image 2</option>
<option value="3">Image 3</option>
</select>
</form>
</div>
<div class="image__content">
<div class="images">
<img class="image image-4">
<img class="image image-5">
<img class="image image-6">
</div>
<form>
<select class="image_select">
<option value="4">Image 4</option>
<option value="5">Image 5</option>
<option value="6">Image 6</option>
</select>
</form>
</div> $('.image__content').each(function() {
var s = $('form').find('.image_select').val();
console.log(s);
var imageId = '.image-'+ s;
$(".image").hide();
$(imageId).show();
});发布于 2020-05-17 13:09:35
value
.image__content的每个,而目标为内部元素时,总是使用$(***, this);引用父元素,意思是:“这个特定的CSS类.is-active的后代,用于处理活动图像的状态,.trigger()到initf 214。
$('.image__content').each(function() {
const $images = $('.image', this); // Cache your selectors
const $select = $('.image__select', this); // Reference using: this
$select.on('change', function() {
const $img = $images.filter(`#${this.value}`); // Get the one!
$images.not($img).removeClass("is-active"); // Hide other images
$img.addClass("is-active"); // Show the one!
}).trigger('change');
});.image__content .image {
display: none;
}
.image__content .image.is-active {
display: block;
}<div class="image__content">
<div class="images">
<img id="a_1" class="image" src="https://placehold.it/100x100/0bf?text=1">
<img id="a_2" class="image" src="https://placehold.it/100x100/f0b?text=2">
<img id="a_3" class="image" src="https://placehold.it/100x100/b0f?text=3">
</div>
<select class="image__select">
<option value="a_1">Image 1</option>
<option value="a_2">Image 2</option>
<option value="a_3">Image 3</option>
</select>
</div>
<div class="image__content">
<div class="images">
<img id="b_1" class="image" src="https://placehold.it/100x100/fb0?text=4">
<img id="b_2" class="image" src="https://placehold.it/100x100/bf0?text=5">
<img id="b_3" class="image" src="https://placehold.it/100x100/0fb?text=6">
</div>
<select class="image__select">
<option value="b_1">Image 4</option>
<option value="b_2">Image 5</option>
<option value="b_3">Image 6</option>
</select>
</div>
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
https://stackoverflow.com/questions/61852058
复制相似问题