使用jquery时,我经常在事件、函数等中使用$(this)
。
最近我尝试了以下方法:
function btn_edit_click (event) {
alert(event.data.idnum);
}
$(".btn_edit").on("click", { idnum: $(this).attr("title") }, btn_edit_click);
由于某种原因,我得到了整个页面的标题,而不是 $(".btn_edit")
引用的元素。我做错了什么,还是这是预期的行为?
最佳答案
这取决于这段代码嵌套在什么内容中。如果答案为空,则 this
引用 window
对象。
如果您在事件处理程序中引用 this
,则 this
将引用触发事件的元素。但看起来好像您正在全局空间中使用 this
。
如果您希望在回调函数中可以访问 .btn_edit
元素的标题,只需在回调函数中引用 this
(注意它如何将您的代码简化为好吧):
function btn_edit_click (event) {
alert(this.title);
//UPDATE: I changed $(this).attr('title') to this.title because it performs much faster
}
$(".btn_edit").on("click", btn_edit_click);
这是一个演示:http://jsfiddle.net/gRK3z/
这里还有一个性能测试,显示使用 .attr('title')
和 .title
之间的差异:http://jsperf.com/jquery-attr-title-vs-title
关于jquery on() 数据参数 - $(this) 指整个文档,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/8811077/