我基本上在一个页面上设置了两个轮播。
我希望能够从第二个轮播项目 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 active .img src 属性。
最佳答案
我想您正在渲染多个轮播项目,并使用 active
类标记您想要通过 JS 函数更改的项目。
如果这是真的,那么您在渲染轮播项目内的不同图像时遇到问题,您正在为所有这些项目分配 main_image
id。
这样,当您调用 jquery $('#main_image').attr
函数时,它不知道需要更改的元素是什么,因为 id main_image
code> 不是唯一的。
当您处于您选择的循环迭代时,您可以仅渲染 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">
或者您可以通过选择 active
类下的 id main_image
使 JQuery 选择器更加具体:
$('.active #main_image').attr('src', img);
关于javascript - HTML 在事件时设置轮播图像 src,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48338046/