当前元素的警报ID [英] Alert ID of current element
问题描述
我正在使用以下代码提醒当前元素的ID。
I'm using following code to alert id of current element.
<input type="text" id="desc" name="txtTitle" onclick="fun()">
jquery:
function fun () {
var currentId = $(this).attr('id');
alert(currentId);
}
为什么警报未定义?
我试过:
Why does it alert "undefined"? I have tried with:
var currentId =$('element').attr('id');
// and
alert($(this).id);
// and
alert(this.id);
但它会提醒 undefined
推荐答案
尝试将其更改为:
<input type="text" id="desc" name="txtTitle" onclick="fun.call(this)">
更好的是,将事件处理程序与jQuery绑定,因为无论如何你都在使用它:
Better, bind your event handler with jQuery, since you're using it anyway:
$(function() { $('#desc').click(fun); });
您的代码不起作用的原因是您正在调用 fun ()
来自浏览器为onclick属性构造的事件处理函数内部。只需调用这样的函数,就不会提供接收器对象—什么这个
,就是这样。如果你用 .call()
调用它,但你可以明确地这样做。
The reason your code doesn't work is that you're calling fun()
from inside the event handler function constructed by the browser for your "onclick" attribute. By just calling the function like that, you provide no "receiver" object — nothing for this
to be, that is. If you call it with .call()
however you can explicitly do that.
这篇关于当前元素的警报ID的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!