我正在研究jQuery中的一个难题。我发现了如何生成随机数,但现在我想迭代这些数字,如果数字是偶数则将它们加粗。
$("button").on("click", function() {
var countNumbers = Number($("input[type=number]").val());
for (var i = 0; i < countNumbers; i++) {
var rand = Math.floor(Math.random() * 15000);
$("#numbers").text($("#numbers").text() + rand + " ");
}
var numbers = $("#numbers").text().split(' ');
for (var i = 0; i < numbers; i++) {
if (Number(numbers[i]) % 2 === 0) {
numbers[i] = "<span class='bold'>" + numbers[i] + "</span>";
}
}
$("#numbers").html(numbers.join(' '));
});
似乎bold
类没有被添加到任何元素中。任何想法为什么它不起作用?
答案 0 :(得分:3)
您需要将循环条件更改为i < numbers.length
,使用 length
属性来获取数组大小
$("button").on("click", function() {
var countNumbers = Number($("input[type=number]").val());
for (var i = 0; i < countNumbers; i++) {
var rand = Math.floor(Math.random() * 15000);
$("#numbers").text($("#numbers").text() + rand + " ");
}
var numbers = $("#numbers").text().split(' ');
for (var i = 0; i < numbers.length; i++) {
//------------------------^-----------
if (Number(numbers[i]) % 2 === 0) {
numbers[i] = "<span class='bold'>" + numbers[i] + "</span>";
}
}
$("#numbers").html(numbers.join(' '));
});
.bold {
font-weight: bold
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<input type="number" />
<button>Generate Numbers</button>
<p id="numbers"></p>
更新:您可以减少代码并使其更简单
$("button").on("click", function() {
var countNumbers = Number($("input[type=number]").val());
var res = [];
// array for storing the random number
for (var i = 0; i < countNumbers; i++) {
var rand = Math.floor(Math.random() * 15000);
// generating random number
res.push(rand % 2 == 0 ? "<span class='bold'>" + rand + "</span>" : rand);
// checking even or odd and wrapping by span if needed finally pushing the string to array
}
$("#numbers").html(res.join(' '));
// joining the array value and set it as html
});
.bold {
font-weight: bold
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<input type="number" />
<button>Generate Numbers</button>
<p id="numbers"></p>
答案 1 :(得分:0)
生成随机数,添加范围,将所有数字(粗体或非粗体)收集到字符串中,并将它们立即应用于HTML,这样更容易,更高效:
$("button").on("click", function() {
var countNumbers = Number($("input[type=number]").val());
var randStr = '';
for (var i = 0; i < countNumbers; i++) {
var rand = Math.floor(Math.random() * 15000);
randStr += (rand % 2 === 0 ? "<span class='bold'>" + rand + "</span>" : rand) + ' ';
}
$("#numbers").html(randStr);
});
&#13;
.bold {
font-weight: bold;
}
&#13;
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<input type="number" />
<button>Generate Numbers</button>
<p id="numbers"></p>
&#13;