javascript - jquery.one ("click",函数())

标签 javascript jquery onclick

我试图从 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/

相关文章:

javascript - 隐藏具有多个切换的元素

javascript - onclick 函数有时不会触发它的事件

javascript - 单击触发器时不保留完整动画

javascript - 仅保留解决并忽略被拒绝的 Promise 的值

事件处理程序中的javascript全局变量

javascript - 获取与特定字符串匹配的对象的 json 数组的长度

jquery - 使用 Jquery 一次性禁用所有复选框、所有下拉列表和文本框

javascript - 在关闭页面或单击后退按钮之前提示用户验证的消息

Android:如何检查两个单击按钮中的两个数字是否相等(内存游戏)?

javascript - 悬停悬停文本框在选中时保持固定