我有这样的代码
<img onclick="getTitle();" title="myimg" >
function getTitle()
{
alert(jQuery(this).attr("title");
}
并且它不起作用。有人可以解释如何正确执行此操作吗?这段代码有什么问题。
最佳答案
As @Neal says ,如果你使用jQuery,请正确使用。
<小时/>尽管如此,这里还是解释了为什么您的代码不起作用:
this
指的是函数内部的window
。您可以使用 .call()
显式设置 this
:
<img onclick="getTitle.call(this);" title="myimg" >
<!-- `this` only refers to the element inside the handler -->
或者您必须显式传递元素作为参数:
<img onclick="getTitle(this);" title="myimg" >
那么你也必须改变你的功能:
function getTitle(element) {
alert(element.getAttribute('title'));
}
有关此类事件处理模型的更多信息,read this article on quirksmode.org about early event handlers 。
There is another one这在事件处理程序的上下文中解释了 this
。
最好的是,如果您阅读 all the articles about event handling并了解不同的模型。实际上,您不应该再通过 HTML 属性绑定(bind)事件处理程序。
为了完整起见,如果没有 jQuery,更好的原因是将事件处理程序附加到 DOM 属性。假设你的图片有一个 ID
<img id="myimg" title="myimg" />
必要的 JavaScript 是:
function getTitle() {
alert(this.getAttribute('title'));
}
document.getElementById('myimg').onclick = getTitle;
此代码必须位于 HTML 中的元素之后。
关于javascript - 在 javascript 函数中使用 this,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/6496217/