javascript - 在 jQuery 中识别 $(this)

标签 javascript jquery this

找出 $(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/

相关文章:

用于读取索引 PNG 数据的 JavaScript

javascript - 带有 ajax 选项卡的 TinyMCE

javascript - 取消复选框选择时触发单击事件

javascript - 直接从 anchor 标记调用函数与创建事件 onload 有什么好处和/或缺陷?

javascript - 查找由 "this"表示的具有特定类的元素的子元素

javascript - 为什么回调函数中 "this"指向 "window Object"呢?

php - 验证错误/边界数据

javascript - 图表刻度问题

javascript - jQuery 移动解剖与全尺寸混合?

javascript - 无法读取未定义 REACT 的 setState 属性