簡體   English   中英

只計算一次點擊

[英]Count Click Only Once

這是我的代碼:

<html>
  <body>
    <script>
      var clicks = 0;
      function clickME() {
        clicks += 1;
        document.getElementById("clicks").innerHTML = clicks;
      }    
    </script>

    <p>Clicks: <a id="clicks">0</a></p>
    <button type="button" onClick="clickME()">Click me</button>
    <button type="button" onClick="clickME()">Click me</button>
    <button type="button" onClick="clickME()">Click me</button>
    <button type="button" onClick="clickME()">Click me</button>
  </body>
</html>

我正在嘗試使用我發現的這個例子:

<body>
  <h1>Single click JS Button</h1>
  <button type="submit" onClick="this.disabled = true; return true;">Submit</button>
</body>

我對如何使用onClick="this.disabled = true;感到困惑,因為對於我的代碼,我在編寫 onClick 時已經調用了該函數。我使用了onClick="clickMe()

你可以有兩次onClick嗎? 我想使用onClick="this.disabled = true;因為如果用戶再次單擊按鈕,我不想繼續增加點擊次數。如果他們單擊一次,我只想增加一次然后禁用按鈕或只是不增加計數后。

注意可能的重復

我不認為這是另一個問題的重復,因為 jQuery click() 只有一次,但我使用的是 JavaScript。 我還沒有學過 jQuery( jQuery click() 只有一次)*

請看這里:

 var clicks = 0; function clickME(el) { el.disabled = true; clicks += 1; document.getElementById("clicks").innerHTML = clicks; }
 <p>Clicks: <a id="clicks">0</a></p> <button type="button" onClick="clickME(this)">Click me</button> <button type="button" onClick="clickME(this)">Click me</button> <button type="button" onClick="clickME(this)">Click me</button> <button type="button" onClick="clickME(this)">Click me</button>

addEventListener option once:true - 在你的情況下看起來是一個完美的選擇。

代碼中有更多解釋

 var clicks = 0 function clickME(event) { clicks += 1 document.getElementById("clicks").innerText = clicks // innerText is more suitable in this case if (event.target.className.includes(`auto-disable`)) { event.target.disabled = true // auto disabling if you need it } } document.querySelectorAll(`button`) // select all buttons .forEach( // loop through the elements // addEventListener with options once:true. once option designed exactly for your purposes, to fire event only once el => el.addEventListener(`click`, clickME, {once: true}) )
 <p>Clicks: <a id="clicks">0</a></p> <button type="button">Click me</button> <button type="button">Click me</button> <button type="button" class="auto-disable">Click me</button> <button type="button" class="auto-disable">Click me</button>

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

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