“this”返回的是[对象窗口],而不是元素

"This" is returning [object Window], not the element

本文关键字:元素 窗口 this 返回 对象      更新时间:2023-09-26

我有这个简单的调试代码(还有更多,但这是剥离版本):

function calc(container) {
    console.log(container);
    return 100;
};
$(".replace").text(calc(this));

控制台只是返回window,而不是元素。这是为什么呢?有什么东西阻止jQuery/JavaScript返回元素吗?

因为 calc 方法不是在元素的上下文中调用的,所以你需要使用类似的东西

$(".replace").text(function(){
    return calc(this)
});

在这种情况下,calc 方法在回调方法中调用,其中this引用当前元素。

演示:小提琴

这里的this是指窗口对象

$(".replace").text(calc(this));

你应该使用

$(".replace").text(function(){
    return calc(this); // here this refers to the current element with class replace
});

阅读此关键字

在全局上下文中,thiswindow

> this === window
true

你想要的可能是这样的:

var $replace = $(".replace");
$replace.text(calc($replace));

只是另一种选择,因为您正在寻找元素,只需使用函数引用本身作为文本的参数。

function calc() {
    console.log(this);
    return 100;
};
$(".replace").text(calc);

错。

因为当您调用该函数时,当前范围是窗口。

如果要使用该元素,请改用函数参数。

参考 j查询集文本