找出 $(this)
当前在 jQuery 中等于什么的最好方法是什么?
例如 alert(this);
没有多大帮助。
我问的原因是一段代码在我将代码移入函数后目前没有做它应该做的事情。
下面的摘录现在在一个函数中,$(this) 现在似乎指的是 DOMWindow。
if($(this).hasClass('open'))
{
alert('I should be closed');
$(this).removeClass('open').addClass('closed');
$(this).parents('article').css('border', '1px solid red').animate({'width': '212px'}, 100, "linear", function() {
run_masonry();
});
}
else
{
alert('I should be open');
$(this).removeClass('closed').addClass('open');
$(this).parents('article').css('border', '1px solid blue').animate({'width': '646px'}, 100, "linear", function() {
run_masonry();
});
}
如何将它保持为 $(this) 作为原始点击元素?
最佳答案
Whats the best way to find out what
$(this)
currently equals in jQuery?
通过将其记录到您最喜欢的 javascript 调试工具的控制台(例如 FireBug 或 Chrome 开发人员工具栏):
console.log($(this));
这将返回一个 jQuery 包装对象。如果您想了解更多关于原生对象的信息,您可以使用:
console.log(this);
如果您正在进行 javascript 开发,您应该使用 javascript 调试工具。 alert
不是这样的工具。
现在您已经使用一些代码源更新了您的问题,看来您正在全局范围内使用 $(this)
。然后它将引用 window
对象。如果你想让它引用一些被点击的元素或者你必须首先订阅 .click 事件的东西:
$('.someSelector').click(function() {
// here $(this) will refer to the original element that was clicked.
});
或者如果您想在单独的函数中外部化此代码:
function foo() {
// here $(this) will refer to the original element that was clicked.
}
$('.someSelector').click(foo);
或:
function foo(element) {
// here $(element) will refer to the original element that was clicked.
}
$('.someSelector').click(function() {
foo(this);
});
关于javascript - 在 jQuery 中识别 $(this),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/8756409/