【问题标题】:JavaScript Why my global array becomes empty? Console.log shows the correct value for a brief momentJavaScript 为什么我的全局数组变空了? Console.log 会在短时间内显示正确的值
【发布时间】:2018-01-02 21:59:02
【问题描述】:

我无法弄清楚这里出了什么问题,我确信这很简单,但是搜索它并不容易,所以如果这个问题已经在其他地方得到了回答,我深表歉意。

情况:

我在我的 js 文件顶部声明了一个全局数组:

var question_ids = [];

数组得到一些值:

$(".quiz-game-container .row").each(function(loop_index) {
    question_ids.push($(this).attr('id'));
}

现在我想显示一个计数器,它有数组的长度:

$(document).ready(function() {
    // Sets the question info how many questions in total
    console.log(question_ids.length);
    $(".quiz-game-container .quiz-container .current-question-number").html("1/", question_ids.length);
});

问题

奇怪的是,我在浏览器开发者控制台中看到了正确的 console.log 输出(长度为 10),但它在 1 秒后消失(可能是所有内容都已加载)并且没有任何值,我在 html 视图中获取 1/

下面是消失的 console.log 的一个活生生的例子: my website

点击刷新按钮F5 并查看控制台,console.log 输出将显示片刻然后消失。

编辑

点击刷新按钮F5 并查看控制台,console.log 输出将显示片刻然后消失。

这似乎是浏览器问题。它在 FireFox 上运行良好。

【问题讨论】:

  • 缺少一些代码。数组如何填充值?
  • @Pointy 你有question_ids.push($(this).attr('id'));
  • $(".quiz-game-container .quiz-container .current-question-number").html("1/" + question_ids.length);
  • 尝试使用.text("1/" + question_ids.length)
  • 消失了是什么意思?您使用的是哪个浏览器?通常,当您刷新页面时,控制台会被清除。

标签: javascript jquery


【解决方案1】:

$.html 只接受一个参数:http://api.jquery.com/html/

改变这个:

.html("1/", question_ids.length);

到这里:

.html("1/" + question_ids.length);

【讨论】:

  • 谢谢!但是为什么console.log输出消失了呢?
【解决方案2】:

替换("1/", question_ids.length) 和: ("1/" + question_ids.length)。 您想要连接两个变量,而不是为 .html() 函数分配两个值。

【讨论】:

  • 谢谢!但是为什么console.log输出消失了呢?
  • 它不能从控制台中消失。你这是什么意思?
  • 对我来说它并没有消失。你用什么浏览器?
  • 我使用 Chrome,在 Firefox 上输出保持不变。好像是浏览器的问题。
  • 我已经用 Chrome 和 Firefox 进行了测试,它们都可以工作。
【解决方案3】:

替换这部分

.html("1/", question_ids.length)

.html("1/" + question_ids.length)

【讨论】:

  • 为什么会有帮助?
  • 因为 , 是方法参数的分隔符而不是连接运算符。
猜你喜欢
  • 1970-01-01
  • 2018-06-16
  • 1970-01-01
  • 2021-01-12
  • 2022-11-15
  • 1970-01-01
  • 2011-11-20
  • 1970-01-01
  • 2021-05-30
相关资源
最近更新 更多