javascript - 在 javascript 函数中使用 this

标签 javascript jquery

我有这样的代码

<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/

相关文章:

javascript - 从 HTML 表单上传 3 张图片。通过 Javascript 将图像发送到 PHP 以上传

javascript - 更改表格行的颜色 onclick 并更改回 onclick

javascript - 如何强制 Bootstrap 表的大小调整得比其父容器宽?

javascript - jQuery 插件选项

javascript - Handlebars 预编译模板未使用 Grunt.js 命名

javascript - AJAX 加载内容后滚动条不起作用

JavaScript - 构造函数调用如何知道如何将 "self"变量添加到返回的对象?

javascript - 如何同步 jQuery 对话框以像 Javascript 的 alert()

javascript - jQuery 最接近 ('tr' ) 在 iOS 中不起作用

javascript - 使用 KO 禁用\启用 Bootbox 按钮