user2054833
user2054833

Reputation: 2165

Getting reference to element that invoked inline function with JQuery

I am inserting elements into the DOM populated with some data I retrieved from a web service. I attached an inline click event to call a function when invoked. The problem is I am not getting a reference to the element that invoked that function.

Code that appends the new elements:

$.getJSON("/search?" + $(this).serialize(), function (data) {
  if (data != null) {
    $.each(data, function (index, video) {
      resultItem.append("<li ><a onclick='loadNewVideo(e)' href='play?video=" + video.video_id + "'>" + "<img width='185' src='" + video.defaultImg + "'/>" + "<span class='video_left_title'>" + video.song.song_name + "<h6 class='artist_name'>" + video.artist.artist_name + "</h6></span></a>");
    });
  }
});

Function:

function loadNewVideo (e) {
     e.preventDefault();
     alert($(this).attr("href"));
}

Upvotes: 0

Views: 254

Answers (3)

user6854719
user6854719

Reputation:

jQuery's event object allowed me to grab what the documentation calls the 'current DOM element within the event bubbling phase'.

var originatingElement = event.currentTarget;

Upvotes: 0

satchmorun
satchmorun

Reputation: 12477

Inline onclick handlers don't go through jQuery, which is why you don't have access.

You can either leave those there and change the handler:

function loadNewVideo(e) {
  e.preventDefault();
  alert($(e.target).attr("href"));
}

Or, and more preferably, don't use the inline handlers. Just give the a elements a class of video (or whatever) and install handlers with jQuery:

...
resultItem.append("<li><a class='video' href=...'")
...

// and elsewhere
$(resultItem).on('click', 'a.video', loadNewVideo);

Upvotes: 0

bfavaretto
bfavaretto

Reputation: 71918

Instead of using inline event handlers, you could delegate the clicks on all a to resultItem:

// Call this only once, when resultItem is already in the DOM
// (for example, on a document.ready callback)
resultItem.on('click', 'a', loadNewVideo);

// Proceed with your current code (slightly modified):
function loadNewVideo (e) {
     e.preventDefault();
     alert($(this).attr("href"));
}

$.getJSON ("/search?" + $(this).serialize(),function (data) {
    if (data != null) {
        $.each (data,function (index,video) {
            resultItem.append("<li ><a href='play?video=" + video.video_id +"'>"
               + "<img width='185' src='"+video.defaultImg +"'/>"
               + "<span class='video_left_title'>"+ video.song.song_name
               + "<h6 class='artist_name'>"+video.artist.artist_name
               + "</h6></span></a>");
         });
    }
});

Upvotes: 1

Related Questions