GJain
GJain

Reputation: 5093

jquery - conflcting/multiple $(this)My in same function

My Code looks like

  $(".div-text").click(function(e) {
    e.preventDefault();
    $(this).parents(".items").find("img.mainImage").each(function() {
       // following this should correspond to mainImage elements and not outside "this"
       alert($(this).data("src")) ----------> **this "this" does not work**
    })
  });

How can I have two this corresponding to different elements or

what is the alternative for code above???

Upvotes: 0

Views: 33

Answers (1)

Arun P Johny
Arun P Johny

Reputation: 388316

this inside the each loop refers to the current mainImage which is being looped through not the clicked div-text element.

A possible solution is to use a closure variable as shown below

$(".div-text").click(function (e) {
    e.preventDefault();
    var self = this;
    $(this).parents(".items").find("img.mainImage").each(function () {
        // following this should correspond to mainImage elements and not outside "this"
        alert($(self).data("src"))
    })
});

Upvotes: 1

Related Questions