JQuery $(this)不能在函数参数中工作

JQuery $(this) not working inside a function parameter

本文关键字:函数 参数 工作 不能 this JQuery      更新时间:2023-09-26

下面的代码不起作用:

$(".countdown").circularCountdown({
    startDate:$(this).attr('data-start'),
    endDate:$(this).attr('data-end'),
    timeZone:$(this).attr("timezone")
});

下面这个可以,

$(".countdown").circularCountdown({
    startDate:$(".countdown").attr('data-start'),
    endDate:$(".countdown").attr('data-end'),
    timeZone:$(".countdown").attr("timezone")
});

我不明白,$(this)是不是引用了"。倒计时"因为我在这个元素上调用函数?有人能帮我一下吗?

因为this不指向countdown,所以一个解决方案是使用each()

$(".countdown").each(function () {
    $(this).circularCountdown({
        startDate: $(this).attr('data-start'),
        endDate: $(this).attr('data-end'),
        timeZone: $(this).attr("timezone")
    });
})

$(this)通常绑定到被点击、悬停等操作的元素上。我认为,在使用$(this)选择器之前,必须指定或选择具有'data-start'属性的元素。你能提供更多关于你是如何运行这个函数和你的html结构的信息吗?

你不是在调用函数,你是在调用插件。所以你写的json参数不知道对象是什么。我非常同意Arun P Johny的观点。如果你想更深入你可以在插件中修改这些值

 startDate: $(this).attr('data-start'),
 endDate: $(this).attr('data-end'),
 timeZone: $(this).attr("timezone")

它会工作的:)

在你的对象初始化器中,"this"指的是当前执行函数的执行上下文,这是你调用circularCountdown的函数,或者(这是我认为最有可能的情况)默认的全局上下文,如果调用不在函数内部。

你可以这样解决你的问题:

 $(".countdown").each(function() {
       var start = $(this).attr('data-start'),
              end = $(this).attr('data-end'),
              time = $(this).attr("timezone");
       $(this).circularCountdown({
            startDate: start,
            endDate: end,
            timeZone: time
      });
 });

jQuery的each方法允许你传入一个函数来依次初始化每个元素,并通过this来访问当前正在初始化的元素。

您正在(几乎)同时执行$(".countown")$(this)。因此,当调用$(".countown")

时,this指向它所指向的对象。<<p> 视觉例子/strong>
var currentThis = this;
$(".countdown").circularCountdown({
    startDate:$(this).attr('data-start'), // "this" is the same as "currentThis"
    endDate:$(this).attr('data-end'),
    timeZone:$(this).attr("timezone")
});

你可能在想传递回调的jQuery函数。在这种情况下,jQuery在回调中设置this,使其指向调用该函数的对象。就像Arun提到的$.each

另一个解决方案是将其保存到一个变量中,因为您不希望运行相同的查询四次。

var ctDown = $(".countdown");
ctDown.circularCountdown({    
    startDate: ctDown.attr('data-start'),
    endDate: ctDown.attr('data-end'),
    timeZone: ctDown.attr("timezone")
});