jQuery: $(this).attr('id') not find id of element -
jQuery: $(this).attr('id') not find id of element - undefined
我试图得到id,只是简单地提醒它onclick虽然它只是"未定义"…你能帮我吗?重要的代码:HTML:
<img src="/pictures/picture.jpg" class="r-gal-photo" id='1' onclick="alertme()" />
function alertme() {
alert($(this).attr('id'));
}
你能看出问题所在吗?我不能……我的缺点:对不起,我想简化代码,我没有意识到我使用"alert()"作为自定义函数的名称。
首先要解决的问题是函数名,我怀疑它在您的实际代码中是不同的,因为否则您就不会得到那么远。
您使用了老派的"onclick"属性将函数与元素关联起来。没有什么能保证this
会像您期望的那样绑定到元素。您可以更改元素:
最好使用jQuery来绑定处理程序:
$("#1").on("click", function() {
alert(this.id);
});
问题
是,正如其他人所说-this
关键字的上下文
this
在CALL本身中引用DOM元素(正如您所认为的那样),但是一旦调用alertme()
,它就不在其作用域中定义了。你可以看看JS:
function alertme(){
alert($(this).attr('id'));
console.log(this);
}
和这个HTML标记:
<img src="/pictures/picture.jpg" class="r-gal-photo" id='abc' onclick="console.log(this); alertme()" />
你会看到你首先在控制台中得到元素,然后在警告'undefined'中,然后在控制台中得到窗口。
要修复它
,您可以使用javaScript的function .prototype.call()函数在调用中指定this
的含义:仅在HTML中将标记更改为
<img src="/pictures/picture.jpg" class="r-gal-photo" id='abc' onclick="alertme.call(this)" />
,它将与您的alertme()一起工作。
或者您可以像这样将this
传递给alertme
:
function alertme(elem){
alert($(elem).attr('id'));
}
HTML: <img src="/pictures/picture.jpg" class="r-gal-photo" id='abc' onclick="alertme(this)" />
来源:
理解jQuery中的"this"的好文章
这个在JS中由on标记绑定
相关文章:
- 如何将HTML id分配给元素,以及如何将JavaScript应用于元素
- difference between '$(<%= DDL.ID %>) & $('
- 使用Javascript获取所选选项ID
- 根据id将json数组组合为一个json数组
- 是否有一个JS/jQuery函数可以获取某个类的每个元素的ID
- 对id以某个字符串开头的元素进行计数
- 如果元素's的ID以数字开头
- 通过id和class属性获取元素
- JQuery appendTo Div with ID instead of appendTo('body
- jqgrid / Validation of ID
- 使用id of li从ul中删除li
- JavaScript Getting ID of A Div
- Can't get ID of 'this' variable
- ID of an event (Fullcalendar)
- 如何查询id IN [some-array-of-numbers]"在azure移动服务中(服务器脚本)
- javascript get id of "commonAncestorContainer"
- 如何循环遍历Array of Objects以查找ID,然后返回一个兄弟键
- jQuery draggables - get id of dragable
- jQuery: $(this).attr('id') not find id of element -
- Get First Span of a <div> using the data-id