【问题标题】:set image as a background of a sibling element将图像设置为兄弟元素的背景
【发布时间】:2013-10-19 15:11:30
【问题描述】:

我的目标是让用户选择背景,但我的 js 不起作用。

<div class="step">
</div>

<div id="images">
  <img src="" data-src="">
  <img src="" data-src="">
  <img src="" data-src="">
  <img src="" data-src="">
</div>

<div class="step">
</div>

<div class="step">
</div>

图像 div 是动态的,应始终更改 .step 之前的图像。

这是我的错误 js:

$(document).on('click', '#images img', function(){ 
  var src = $(this).data('src'); 
  $(this).before().find('.step').css("background" , "url("+src+")");  
});

【问题讨论】:

    标签: javascript jquery dom-manipulation


    【解决方案1】:

    我认为您选择的内容是错误的,并且 before() 附加了元素。

    $(this).parent().prev('.step').css("background" , "url("+src+")"); 
    

    基本解释

    $(this)  //the image
        .parent()  // the div #images 
            .prev('.step')  //get the previous sibling with the class step
                .css("background" , "url("+src+")"); 
    

    如果您想要所有 .step 元素,您可以使用 .siblings(".step") 而不是 .prev(".step")

    【讨论】:

      【解决方案2】:

      我认为你想要 prev(),而不是 before()

      【讨论】:

        【解决方案3】:

        $(this).parent() 将为您提供包含图像的 div 和 .prev('.step') 为您提供前一个带有类步骤的元素。 before() 仅用于插入匹配元素集中的每个元素之前。

        $(this).parent().prev('.step').css("background" , "url("+src+")");
        

        【讨论】:

          【解决方案4】:

          .before() method 插入 内容,它没有找到更早的元素。你想要.prev() method,注意它找到了前一个兄弟,所以你需要遍历.parent()

          $(this).parent().prev().css("background" , "url("+src+")");
          

          演示:http://jsfiddle.net/DBRkS/

          请注意,.prev() 在找到匹配元素之前不会向后搜索,如果它与您提供的选择器匹配,它会选择紧邻的前一个兄弟元素,否则它不会返回任何内容。因此,对于您展示的 html,无论是否使用 ".step" 选择器,它都可以正常工作。

          【讨论】:

            猜你喜欢
            • 1970-01-01
            • 1970-01-01
            • 1970-01-01
            • 2017-05-19
            • 2015-01-24
            • 2015-12-12
            • 1970-01-01
            • 1970-01-01
            相关资源
            最近更新 更多