-1

Having trouble using the $(this) object inside an .each()..

Not sure what I'm doing wrong. This works, so its not critical, but I would like to know why it doesn't work with $(this).on("click instead of $("#b_" + thumb_id).on("click"

//Create a flip button for each attached image.
$(".attached_preview").each(function(){
    var att_name = $(this).attr("data-name"), thumb_id = $(this).attr("data-thumb");
    //Create the button
    var element = document.createElement("input");
    element.id = "b_" + thumb_id;
    element.type = "button";
    element.value = "Flip " + att_name;

    //Add button to page
    this.parentNode.appendChild(element);

    // create function for button.
    $("#b_" + thumb_id).on("click",function(e){  //need jQuery object, yet can't use $(this) for some reason. :-(
         e.preventDefault(); e.stopImmediatePropagation(); //needed to stop form submission.
         //reset the <img> src attribute from the saved copy.
         var image = $("#invert"+thumb_id);
         image.attr("src",image.attr("data-url"));
         image.toggleClass("rotated"); //the bit that actually flips.. used to be so simple!
         image.wheelzoom();//Re-enable the zoom
    });
});

Why do I have to re-specify the selector inside the loop?

2 Answers 2

1

It's because $(this) in your code refer to

$('.attached_preview')

so $(this).on("click fire when any element with class .attached_preview has been clicked

where as:

$("#b_" + thumb_id).on("click"

or:

$("#b_" + $(this).attr("data-thumb")).on("click"

fire click event for element with id named #b_ + value of data-thumb attribute receive from your clicked .attached_preview

1
  • The various $(this)/this/etc become confusing.. but I got there, you are correct, and explained better than my pithy response, have the tick Sir.
    – Grizly
    Jan 28, 2014 at 6:13
0

I see it now, its because: element != $(this).. gah.. Well, for posterity.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.