[英]jquery .one("click", function())
我正在尝试从 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>
function changeColor() { $("#box1").one("click", function() { //box.style = "background: " + genColor(); $(this).css("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] }
#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> <div id= "container"> <div class="grid"> <div id= "box1"></div> </div> </div>
您必须对代码进行 2 处更改:
1:将window.onload = changeColor
这一行改为window.onload = changeColor();
(这里你漏掉了函数括号();
)
2:将$("box1").one("click", function()
这一行改为$("#box1").on("click", function()
(这里你错过了 jQuery id 选择器#
和.on
)
工作JSFiddle
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.