javascript - var #theID ="quizChoice"+i.toString() 中出现错误;

标签 javascript html button

我正在尝试创建四个按钮,其中四个标签以随机顺序出现:

<div class="row text-center center-block">
                <button class="quizChoice btn btn-md btn-info" id="quizChoice0"></button>
            </div>
             <div class="row text-center center-block">
                <button class="quizChoice btn btn-md btn-info" id="quizChoice1"></button>
            </div>
             <div class="row text-center center-block">
                <button class="quizChoice btn btn-md btn-info" id="quizChoice2"></button>
            </div>
             <div class="row text-center center-block">
                <button class="quizChoice btn btn-md btn-info" id="quizChoice3"></button>
</div>

标签存储在

var choiceLabels = ["Hola", "Hole", "Holo", "Holu"];

然后代码循环访问选项以将它们粘贴到按钮中:

for (var i=0; i<choiceLabels; i++) {
    var #theID="quizChoice"+i.toString();
    $(theID).text(choiceLabels[i])
};

但是我收到以下错误: 未捕获的语法错误:无效或意外的标记在行

var#theID="quizChoice"+i.toString();

有人知道为什么吗?

最佳答案

当您尝试通过 ID 访问元素时,即您正在 jquery 中尝试 Id 选择器,那么您必须在 id 之前附加 # ,因此在您的情况下它将是

for (var i=0; i<choiceLabels; i++) {
    var theID="#quizChoice"+i.toString();
    $(theID).text(choiceLabels[i])
};

您不需要将 # 放入您的变量中,该变量也在我的答案中更新。即您必须使用 theID

而不是 #theID

关于javascript - var #theID ="quizChoice"+i.toString() 中出现错误;,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49232832/

相关文章:

javascript - 在javascript中模拟双击asp.net按钮

javascript - express 和 Mongoose : Cannot read property 'name' of undefined in Postman

javascript - 如何在文档字段而不是集合字段中将数据添加到 firebase?

javascript - 映射下拉列表选择 URL

html - 为什么我的 CSS Grid 错误?

c# - 对象不是函数错误

jquery - 将 CSS 应用于 jQuery 对话框按钮

javascript - 为什么我的 anchor 标签滚动不流畅?

javascript - 为什么 'getTimezoneOffset' 在 Date.prototype 中实现而不是作为 Date 的静态方法?

html - li active css bug 在我的案例中