我正在尝试创建四个按钮,其中四个标签以随机顺序出现:
<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])
};
但是文字没有出现在按钮上 - 它们保持空白。 有谁知道为什么?
答案 0 :(得分:2)
您的错误在于:i<choiceLabels
。 choiceLabels
是一个数组,因此您必须执行i<choiceLabels.length
。
var choiceLabels = ["Hola", "Hole", "Holo", "Holu"];
for (var i=0; i<choiceLabels.length; i++) {
var theID="#quizChoice"+i.toString();
$(theID).text(choiceLabels[i])
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<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>
答案 1 :(得分:1)
您错过length
中的choiceLabels
值。迭代应循环遍历choiceLabels.length
:
var choiceLabels = ["Hola", "Hole", "Holo", "Holu"];
for (var i=0; i<choiceLabels.length; i++) {
var theID="#quizChoice"+i.toString();
$(theID).text(choiceLabels[i])
};
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<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>