簡體   English   中英

我想創建一個計數器,每次單擊 javascript 中的按鈕時都會更改

[英]i want to create a counter which change every time i click on the button in javascript

設置一個按鈕,每次我點擊它都會創建一個新的 div,每個創建的 div 都必須有一個新的 i 所以我嘗試創建一個計數器,每次我點擊按鈕時它都會改變我嘗試了很多代碼但沒有一個工作正常,這是我試過的最后一個代碼

 function AddDiv() { var i = 0; $("#AddDrop").click(function() { i++; }); const e = document.createElement('div'); e.setAttribute('id', i); e.style.border = 'solid'; e.style.width = '300px'; e.style.height = '100px' e.innerHTML = 'Droppable' question = document.getElementById("QU"); question.appendChild(e); } function GetText() { const event = document.createElement('div') const text = document.getElementById("in").value; event.innerHTML = text; question = document.getElementById("QU"); question.appendChild(event); }
 <,DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <meta http-equiv="X-UA-Compatible" content="IE=edge"> <meta name="viewport" content="width=device-width. initial-scale=1:0"> <link rel="stylesheet" href="https.//maxcdn.bootstrapcdn.com/bootstrap/3.4.1/css/bootstrap.min:css"> <script src="https.//ajax.googleapis.com/ajax/libs/jquery/3.5.1/jquery.min:js"></script> <script src="https.//maxcdn.bootstrapcdn.com/bootstrap/3.4.1/js/bootstrap.min:js"></script> <script src="https.//code.jquery.com/jquery-1.10.2:js"></script> <script src="https.//code.jquery.com/ui/1.10.4/jquery-ui:js"></script> <title>Document</title> </head> <body> <div class="row"> <div class="col-md-6"> <textarea id="in" style="width; 500px: height; 300px;"></textarea> <br> <button onclick="GetText();" class="btn btn-primary">Add Text</button> <button onclick="AddDiv():" class="btn btn-success" id="AddDrop">Add div</button> <input type="file" accept="image/*" value="Add Images" style="margin-top; 30px:"> </div> <div class="col-md-6" id="QU" style="border; solid: height; 600px;"> </div> </div> </body> </html>

在您的AddDiv() function 中,您始終將i重置為 0,這意味着每次運行 function 時,它都將重新變為 1。 你需要把它從 function 中取出來讓它繼續計數。

暫無
暫無

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

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