[英]jQuery event target element attribute retrieval
我在從事件目標元素中提取屬性時遇到了一些麻煩。
我正在使用php訪問mysql數據庫。 從查詢中,我提取了一些圖像文件名及其各自的ID。 然后,我在帶有以下行的表中顯示這些圖像:
print '<td><img id="img_' . $row['paint_id'] . '" class="thumb_target" src="img/paint/thumb/' . $row['paint_thumb'] .'"></td>';
如您所見,此行為每個圖像賦予ID'img_xx',其中xx是sql數據庫中圖像的數字ID。 我還為每個圖像提供了“ thumb_target”類。 准備好文檔后,我為thumb_target元素設置了一個.click事件。 這將進行AJAX調用,該調用應將img_xx id作為數據傳遞。 我得到了這個在鉻使用
data: 'imgID=' + event.target.id
但是,幾個小時后,我決定在firefox中檢查其他內容,發現它不適用於所有瀏覽器。 使用jQuery的方法:
var id = $(this).attr('id');
我無法獲得的ID只能是未定義的。 我針對的元素與我認為的元素不同嗎?
這是相關的javascript:
function runClick() {
var id = $(this).attr('id');
alert(id);
$.ajax({
url: 'overlay.php',
//~ data: 'imgID=' + event.target.id,
//~ data: ({ imgID: id }),
data: 'imgID=' + id,
dataType: 'json',
success: function(data, textStatus, jqXHR) {
processJSON(data);
},
error: function(jqXHR, textStatus, errorThrown){
alert("Failed to perform AJAX call! textStatus: (" + textStatus +
") and errorThrown: (" + errorThrown + ")");
}
});
}
$(document).ready( function() {
$('.thumb_target').click( function() {
runClick();
});
$('#overlay').hide();
});
這是測試頁面的鏈接: http : //www.carlthomasedwards.com/painting2.php
runClick
在全局范圍內執行,因此this
是指全局對象( window
)。
改用它:
$('.thumb_target').click( function(event) {
runClick.apply(this);
});
甚至更簡單:
$('.thumb_target').click( runClick);
當瀏覽器執行runClick
,不會保留this
上下文。 如果您在暫停Chrome的調試器 ,你可以看到, this
實際上是Window
時runClick
被調用。
繞過該問題的方法是將元素傳遞到runClick
:
function runClick(elem) {
alert($(elem).attr('id'));
...
}
和
$('.thumb_target').click( function() {
runClick(this);
});
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.