Javascript设置超时未按预期工作
我有一个小功能:Javascript设置超时未按预期工作,javascript,jquery,Javascript,Jquery,我有一个小功能: function showVotingModal(e) { var $collector = $("#vote-collector"); setTimeout(function () { $collector.addClass("open"); }, 5000); $collector.find(".description").text($(this).data("desc")); $collector.attr(
function showVotingModal(e) {
var $collector = $("#vote-collector");
setTimeout(function () {
$collector.addClass("open");
}, 5000);
$collector.find(".description").text($(this).data("desc"));
$collector.attr("data-id", "15");
}
其想法是在延迟5秒后显示#投票收集器面板,并用面板填充更多数据
上面的代码可以工作,但是下面的代码不行
function showVotingModal(e) {
setTimeout(function () {
var $collector = $("#vote-collector");
$collector.addClass("open");
$collector.find(".description").text($(this).data("desc"));
$collector.attr("data-id", "15");
}, 5000);
}
在这种情况下,不会填充“description”标记
有人能告诉我是我做错了什么,还是超时功能根本就不能这样工作
谢谢尝试将外部作用域绑定到
设置超时
function showVotingModal(e) {
setTimeout(function () {
var $collector = $("#vote-collector");
$collector.addClass("open");
$collector.find(".description").text($(this).data("desc"));
$collector.attr("data-id", "15");
}.bind(this), 5000);
}
在setTimeout
内部,默认情况下,此
将被视为窗口
或者您可以使用另一个签名setTimeout
,该签名在延迟后接受附加参数
function showVotingModal(e) {
setTimeout(function (that) {
var $collector = $("#vote-collector");
$collector.addClass("open");
$collector.find(".description").text($(that).data("desc"));
$collector.attr("data-id", "15");
}, 5000, this);
}
问题应该与代码
$(this.data(“desc”)
这将指向您使用的两种情况中的不同上下文/对象
尝试使用bind作为setTimeout。您使用的代码中有一个非常小的错误,它当前指向当前函数范围。 你只需要用下面的代码更新你的函数
function showVotingModal(e) {
var self = this;
setTimeout(function () {
var $collector = $("#vote-collector");
$collector.addClass("open");
$collector.find(".description").text($(self).data("desc"));
$collector.attr("data-id", "15");
}, 5000);
}
显示什么错误?在setTimeout回调中,
此
指的是窗口
。您需要使用closure在$collector.find(“.description”).text($(this.data(“desc”))中的this
是什么代码>。我认为它超出了超时函数的范围。“this”,在本例中,如果单击了“”元素。bind
是属于function-prototype
的函数,它工作得很好,我也受过教育。@JohnOhara很乐意帮助!:)