Frage

my goal is to let the user to choose the background, but my js doesn;t work.

<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>

The images div is dynamic and should always change the image of the .step just before.

here is my buggy js:

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

Lösung

I think what you are selecting is wrong and before() appends elements.

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

basic explanation

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

If you want all of the .step elements, you would use .siblings(".step") instead of .prev(".step")

Andere Tipps

I think you want prev(), not before()

$(this).parent() will give you the div which holds the images & .prev('.step') gives you the previous element with class step. before() is only used to insert before each element in the set of matched elements.

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

The .before() method inserts content, it doesn't find an earlier element. You want the .prev() method, noting that it finds the previous sibling so you need to traverse via the .parent():

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

Demo: http://jsfiddle.net/DBRkS/

Note that .prev() doesn't search backwards until it finds a matching element, it selects the immediately preceding sibling if it matches the selector you supply, otherwise it returns nothing. So for the html you've shown it would work the same with or without the ".step" selector.

Lizenziert unter: CC-BY-SA mit Zuschreibung
Nicht verbunden mit StackOverflow
scroll top