簡體   English   中英

jquery .one("click", function())

[英]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.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM