![](/img/trans.png)
[英]how to make javascript load new data every time (without using cache data) when I redirect it to a handler(page) on mouse click
[英]JavaScript / HTML work with DOM, Button which count click and make new string every time when I click
我需要創建計數點擊但每次創建新字符串的按鈕。 我有這個函數,每次點擊時都會計數,但我不明白,為什么在 HTML 中它每次計數為零,應該是這樣的:(垂直每次點擊都會產生更新計數的新字符串) 1 2 3 4 。 ..
<form action="#">
<input type="button" value="Count" onclick="add_count()">
</form>
function add_count() {
let integer = (function () {
let counter = 0;
return function() {return counter++;};
}());
let tag = document. createElement("p");
let text;
text = document. createTextNode(integer());
tag. appendChild(text);
let element = document. getElementsByTagName("body")[0];
element. appendChild(tag)};
您只需要將counter
初始化移到函數范圍之外
我已經稍微調整了你的代碼。
注意:盡量不要使用內聯事件監聽器,而是在 JavaScript 文件中使用事件監聽器
let counter = 0; const button = document.querySelector('input'); function add_count() { let integer = (() => counter++); const tag = document.createElement("p"); const text = document.createTextNode(integer()); tag.appendChild(text); const element = document.body element.appendChild(tag) }; button.addEventListener('click', add_count)
<form action="#"> <input type="button" value="Count"> </form>
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.