javascript 作用域,为什么 $(this) 等于 [window]? [英] javascript scope, why does $(this) equal [window]?
问题描述
我有一个 ajax 函数(不确定是否相关),可以更新 html 并创建一些链接:
I have an ajax function (not sure if relevant) that updates html and creates a few links:
<a href="#" class="clickme" onclick="column_click()" title="my title">click me</a>
我不知道为什么,但是 onclick,如果我提醒 $(this).attr('title')
它显示为 undefined
,如果我提醒$(this)
它显示 [window]
I'm not sure why, but onclick, if I alert $(this).attr('title')
it shows as undefined
, and if I alert $(this)
it shows [window]
function column_click(){
value = $(this);
console.log(value);
thetitle= $(this).attr('title');
console.log(thetitle);
}
有人知道为什么会这样吗?
Does anyone know why this is the case?
推荐答案
您混淆了 JS/jQuery 事件处理的显式和非显式样式.在不显眼的风格中,您在 JavaScript 本身中设置点击处理程序,而不是在 onclick
属性中:
You're confusing the obtrusive and unobtrusive styles of JS/jQuery event handling. In the unobtrusive style, you set up click handlers in the JavaScript itself, rather than in an onclick
attribute:
$('.clickme').on('click', column_click);
上面的代码会在处理事件时自动将this
绑定到被点击的元素上.
The above will automatically bind this
to the clicked element while the event is being handled.
然而,这不是标准的 JavaScript!这是 jQuery 的一个特性.on
方法足够智能,可以在处理事件时将函数绑定到 HTML 元素.onclick="column_click"
不这样做,因为它不是 jQuery.它使用标准的JS行为,默认将this
绑定到全局对象window
.
However, this is not standard JavaScript! It's a feature of jQuery. The on
method is smart enough to bind the function to the HTML element when it handles the event. onclick="column_click"
doesn't do this, because it isn't jQuery. It uses standard JS behavior, which is to bind this
to the global object window
by default.
顺便说一下,你看到 [window]
的原因是 $(this)
已经将 window
包裹在一个 jQuery 对象中,所以它看起来像一个包含 window
对象的数组.
By the way, the reason you see [window]
is that $(this)
has wrapped window
in a jQuery object, so it looks like an array with the window
object inside it.
解决您的问题主要有以下三种方式:
There are three main ways to deal with your problem:
- 使用不显眼的绑定:
$('.clickme').on('click', column_click);
在页面末尾的脚本中,或$(文档).ready
处理程序 - 手动绑定
this
:onclick="column_click.call(this)"
完全避免使用
this
:
- Use unobtrusive binding:
$('.clickme').on('click', column_click);
in a script at the end of the page, or somewhere in the$(document).ready
handler - Bind
this
manually:onclick="column_click.call(this)"
Avoid using
this
at all:
function column_click(e) {
var value = $(e.target);
//...
其中,为了良好的编码,我强烈推荐 1 或 3.
Of these, I'd strongly recommend either 1 or 3 for the sake of good coding.
这篇关于javascript 作用域,为什么 $(this) 等于 [window]?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!