0

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"));
}
4

3 に答える 3

1

aインライン イベント ハンドラーを使用する代わりに、すべてのクリックを次のようにデリゲートできます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>");
         });
    }
});
于 2013-02-14T01:55:35.250 に答える
0

インラインonclickハンドラーは jQuery を経由しないため、アクセスできません。

それらをそのままにして、ハンドラーを変更できます。

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

または、インライン ハンドラを使用しないことをお勧めします。a要素にvideo(またはその他の) クラスを指定し、jQuery を使用してハンドラーをインストールするだけです。

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

// and elsewhere
$(resultItem).on('click', 'a.video', loadNewVideo);
于 2013-02-14T01:47:20.363 に答える