我一直在尋找一段時間,我發現我可以將一個值從 doGet 發送到創建的 html。
但我想做一些不同的事情,我想要一個按鈕和標簽,每次按下該按鈕時它都會增加標簽。
類似于按下該按鈕的計數器。
我已經有了呈現按鈕和標簽的 HTML,它非常簡單
<!DOCTYPE html>
<html>
<head>
<base target="_top">
<?!= include('stylesheet'); ?>
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>LDP Test</title>
<link rel="stylesheet" href="https://www.w3schools.com/w3css/4/w3.css">
<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>
function incrementCounter() {}
</script>
</head>
<body>
<label> Counter 0 </label>
<button onClick="incrementCounter"> Increment counter</button>
</body>
</html>
我想將 incrementCounter 函式鏈接到這個標簽,或者任何可以做到的 html 元素,只要按下按鈕,它就會遞增并呈現在螢屏上,有人可以指導我完成這個嗎?
uj5u.com熱心網友回復:
您的代碼中有一些錯誤。首先它應該onclick不是onClick,函式應該被稱為onclick="incrementCounter()".
其次,標簽應該與輸入、文本區域或選擇元素一起使用。
現在來看代碼
HTML
<p>Count: <span id="counter">0<span></p>
<button onclick="incrementCounter()">Increment Counter</button>
JS
function incrementCounter() {
const counterElem = document.querySelector('#counter'),
count = counterElem.innerHTML;
counterElem.innerHTML = count 1;
}
代碼中發生的事情是我正在選擇顯示計數的目標元素。然后我得到它的 innerHTML 的值,并 在counterElem.innerHTML. 然后我將值加 1 并將其設定為 innerHTML
uj5u.com熱心網友回復:
試試下面的代碼片段
function incrementCounter() {
document.querySelector('#counter').innerHTML ;
}
<label>Count: <span id="counter">0</span></label>
<button onclick="incrementCounter()">Increment Counter</button>
轉載請註明出處,本文鏈接:https://www.uj5u.com/ruanti/438824.html
