user3151454
user3151454

Reputation: 15

Replacing "this" with real value

Right now I have this piece of code in a function:

oTrack = json.played_tracks[0];

eA = $("<a/>")
.addClass("hugetile")
.attr("href","#"+0)
.appendTo(o)
.click(function(){
    cont.getDetails($(this),"lastsong",18);
    console.log($(this)) 
});

Now: I would like to be able to replace "this" with a real value.

The console.log displays: Object[a.hugetile #0]

However simply replacing "$(this)" with "Object[a.hugetile #0]" results in a big ol' error.

The reason I need it without "this" is because I want the function to instantly perform the .click function (so that it triggers without a user having to click). But at the moment this is impossible because I can't have cont.getDetails($(this),"lastsong",18); as standalone code. (this is unknown)

Upvotes: 0

Views: 72

Answers (2)

Musa
Musa

Reputation: 97707

Simply trigger a click

oTrack = json.played_tracks[0];

eA = $("<a/>")
.addClass("hugetile")
.attr("href","#"+0)
.appendTo(o)
.click(function(){
    cont.getDetails($(this),"lastsong",18);
    console.log($(this)) 
}).click();

Calling

cont.getDetails(eA,"lastsong",18);

right after should work without the flash. eA is equivalent to $(this) in the click handler.

Upvotes: 2

Felix Kling
Felix Kling

Reputation: 816730

Triggering the click event immediately would be the best approach. However, to give you a better understanding of this inside the event handler, you could also do the following:

eA = $("<a/>")
    .addClass("hugetile")
    .attr("href", "#" + 0)
    .appendTo(o)
    .click(function () {
        cont.getDetails($(this), "lastsong", 18);
        console.log($(this))
    });

cont.getDetails(eA, "lastsong", 18);

Inside the event handler, this refers to the DOM element you created with $("<a/>"). But so does eA. eA is a jQuery object which contains that DOM element, hence eA and $(this) are both jQuery objects which contain the same DOM element.

Upvotes: 2

Related Questions