代码之家  ›  专栏  ›  技术社区  ›  Biplov

HTML设置旋转木马图像src(当其处于活动状态时)

  •  0
  • Biplov  · 技术社区  · 7 年前

    我基本上在一个页面中设置了两个旋转木马。

    我希望能够从第二个旋转木马项目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>
    

    当我设置MainImage时,该函数工作正常,并且是控制台。日志给了我正确的图像。我想将该图像设置为我的第一个旋转木马。项目处于活动状态。img src属性。

    1 回复  |  直到 7 年前
        1
  •  1
  •   Cornezuelo del Centeno    7 年前

    我假设您正在渲染多个旋转木马项目,并使用 active 为要由JS函数更改的对象初始化。

    如果这是真的,那么您在渲染carusel项目中的不同图像时会遇到问题,您正在指定 main_image 所有人的id。

    这样,当您调用jquery时 $('#main_image').attr 函数它不知道需要更改的元素是什么,如id main\u图像 不是唯一的。

    您可以只渲染 id='main_image' 当您在循环迭代中时,您可以使用类似于 忙碌的 类别:

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

    或者,您可以使JQuery选择器更具体地选择id main\u图像 那是在 忙碌的 类别:

    $('.active #main_image').attr('src', img);