HTML将Carousel图像src激活时设置

时间:2018-01-19 09:40:09

标签: javascript jquery carousel bootstrap-4

我基本上在一个页面中设置了两个轮播。

我希望能够从第二个轮播项目src onclick更改第一个轮播项目活动src。

我做的是

我的第二个轮播项目如下:

<div style="max-width: 20%; max-height: 20%;" class="col-sm-3">
<img style=" margin-left:100%;border-radius: 8px; height:100px;" src="{{column}}" onclick="setMainImage('{{image}}')" class="img-responsive" alt="test1">

我的第一个旋转木马项目需要根据点击项目的第二个旋转木马进行更改。

<div style="max-width: 100%; max-height: 100%;" class="item{% if loop.index == 1 %} active{% endif %}">
<center>  
<img style="margin:auto;height:400px;" src="{{item}}" id="main_image" class="img-responsive" alt="test1">

<script>
    function setMainImage(img) {            
        console.log(img)
        console.log($('#main_image').attr('src', img)); 
    }
</script>

当我执行setMainImage时,该函数正常工作,console.log为我提供了正确的图像。我想将该图像设置为我的第一个轮播.item活动.img src属性。

1 个答案:

答案 0 :(得分:1)

我想你正在渲染多个轮播项目,并用active类标记你要通过JS函数更改的那个。

如果这是真的,那么在carusel项目中呈现不同的图像时会出现问题,您要为所有这些项目分配main_image id。

这样,当你调用jquery $('#main_image').attr函数时,它不知道它需要改变什么元素,因为id main_image不是唯一的。

当你选择循环迭代时,你可以只渲染id='main_image',就像你对active类所做的那样:

<center><img style="margin:auto;height:400px;" src="{{item}}"{% if loop.index == 1 %} id="main_image"{% endif %} class="img-responsive" alt="test1">

或者,您可以更加具体地选择main_image类下的active ID:

$('.active #main_image').attr('src', img);
相关问题