Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/jquery/71.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Javascript设置超时未按预期工作_Javascript_Jquery - Fatal编程技术网

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很乐意帮助!:)