function generate() { var redBalls = []; while (redBalls.length < 6){ var num = Math.floor(Math.random() * 33) + 1; if (redBalls.indexOf(num) === -1) { redBalls.push(num); } } redBalls.sort(function(a,b){ return a - b; }); var blueBall = Math.floor(Math.random() * 16) + 1; var result = redBalls.map(num => (num < 10 ? '0' + num : num.toString())).join(" ") + " " + (blueBall < 10 ? '0' + blueBall : blueBall.toString()); displayResult(result); } function displayResult(result){ var container = document.getElementById("ball-container"); container.innerHTML = ""; for (var i = 0; i <6; i++) { var ball = document.createElement("div"); ball.classList.add("red-ball"); ball.innerHTML = result.split(" ")[i]; container.appendChild(ball); } var ball = document.createElement("div"); ball.classList.add("blue-ball"); ball.innerHTML = result.split(' ')[6]; container.appendChild(ball); } 更改代码为jQuery
时间: 2024-01-29 11:03:07 浏览: 77
以下是使用 jQuery 改写后的代码:
```
function generate() {
var redBalls = [];
while (redBalls.length < 6){
var num = Math.floor(Math.random() * 33) + 1;
if (redBalls.indexOf(num) === -1) {
redBalls.push(num);
}
}
redBalls.sort(function(a,b){
return a - b;
});
var blueBall = Math.floor(Math.random() * 16) + 1;
var result = redBalls.map(num => (num < 10 ? '0' + num : num.toString())).join(" ") + " " + (blueBall < 10 ? '0' + blueBall : blueBall.toString());
displayResult(result);
}
function displayResult(result){
var $container = $("#ball-container");
$container.empty();
for (var i = 0; i <6; i++) {
var $ball = $("<div>").addClass("red-ball").text(result.split(" ")[i]);
$container.append($ball);
}
var $ball = $("<div>").addClass("blue-ball").text(result.split(' ')[6]);
$container.append($ball);
}
```
其中,`document.getElementById` 改为了 `$()`,`innerHTML` 改为了 `text()`,`document.createElement` 改为了 `$("<div>")`,`classList` 改为了 `addClass()`,`appendChild` 改为了 `append()`,`container.innerHTML = ""` 改为了 `$container.empty()`。
阅读全文