我试图从 jquery 获取 .one,即使再次单击后也只允许更改颜色一次,但我不明白为什么它不起作用。 这是我的 HTML:
<!DOCTYPE html>
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title></title>
<link rel="stylesheet" href="styleSheets/main.css">
<script src = "https://code.jquery.com/jquery-3.4.1.js"></script>
<script src = "js/main.js"></script>
</head>
<body>
<div id= "container">
<div class="grid">
<div id= "box1"></div>
</div>
</div>
</body>
</html>
这是我的 CSS 代码:
#box1 {
width: 100px;
height: 100px;
right: 200px;
background: red;
position: absolute;
}
最后,这是我的 JS:
function changeColor() {
var box = document.getElementById("box1");
$("box1").one("click", function() {
box.style = "background: " + genColor();
});
};
window.onload = changeColor
function genColor() {
var arr = ['blue', 'green', 'yellow', 'teal'];
var x = Math.floor(Math.random() * arr.length - 1);
return arr[x]
}
我试图让我的changeColor函数只工作一次。如果我再次点击它,什么也不会发生。
最佳答案
.one
应为 .on
,然后将事件附加到文档就绪的按钮,以便您可以多次触发 onclick。
$(document).ready(function() {
var box = document.getElementById("box1");
$("#box1").on("click", function() {
box.style = "background: " + genColor();
});
});
function genColor() {
var arr = ['blue', 'green', 'yellow', 'teal'];
var x = Math.floor(Math.random() * arr.length - 1);
return arr[x]
}
#box1 {
width: 100px;
height: 100px;
right: 200px;
background: red;
position: absolute;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<!DOCTYPE html>
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title></title>
<link rel="stylesheet" href="styleSheets/main.css">
<script src="https://code.jquery.com/jquery-3.4.1.js"></script>
<script src="js/main.js"></script>
</head>
<body>
<div id="container">
<div class="grid">
<div id="box1"></div>
</div>
</div>
</body>
关于javascript - jquery.one ("click",函数()),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/59260941/