我在从事件目标元素提取属性时遇到一些问题。
我正在使用 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 作为数据传递。我使用
在 chrome 中让它工作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();
});
最佳答案
runClick
在全局范围内执行,因此 this
引用全局对象(window
)。
使用它来代替:
$('.thumb_target').click( function(event) {
runClick.apply(this);
});
或者更简单:
$('.thumb_target').click( runClick);
关于php - jQuery 事件目标元素属性检索,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/18668197/