gpt4 book ai didi

javascript - jQuery - 将段落中的每个偶数加粗

转载 作者:行者123 更新时间:2023-11-30 12:14:07 25 4
gpt4 key购买 nike

我正在用 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 类似乎没有添加到任何元素中。知道为什么它不起作用吗?

http://jsfiddle.net/rL3y28cm/

最佳答案

您需要将循环条件更改为 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>

关于javascript - jQuery - 将段落中的每个偶数加粗,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32894006/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com