[英]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.