2013-02-14 62 views
0

我將元素插入填充了從Web服務檢索到的一些數據的DOM中。我附加了一個內聯點擊事件來調用時調用一個函數。問題是我沒有得到引用該函數的元素的引用。該追加新要素獲取對使用JQuery調用內聯函數的元素的引用

代碼:

$.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 loadNewVideo (e) { 
    e.preventDefault(); 
    alert($(this).attr("href")); 
} 

回答

1

而不是使用內聯事件處理程序,你可以委託上點擊所有aresultItem

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

在線onclick處理程序不通過jQuery的,這就是爲什麼你沒有訪問。

你可以保留那些有和更改處理程序:

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

或者,更優選,不使用inline處理程序。只是給a元素類的video(或其他),並安裝處理程序使用jQuery:

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

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

第二種方法,它沒有工作 – user2054833 2013-02-14 01:56:41

+0

好點,那些元素將不會在DOM中。編輯我的答案將處理程序附加到resultItem列表。 – satchmorun 2013-02-14 01:59:36