我有一個由 1 填充的按鈕。我希望當我單擊按鈕時,ap 標記填充 1。那是我想用 javascript 編輯一個 html 標記。
<!DOCTYPE html>
<html>
<head>
<style>
body{
background: linear-gradient(to bottom, rgb(75,83,119), rgb(33,35,53));
}
#btn1{
background: linear-gradient(to bottom, rgb(49,87,255), rgb(78,39,255));
box-shadow: 5px 5px 10px black;
border: 0px;
border-radius: 5px;
font-size: medium;
width: 110px;
height: 40px;
text-align: center;
margin(200px,200px,200px,200px);
transition-duration: 0.1s;
}
#btn1:active{
box-shadow: 0px 0px 0px black;
transform: translateY(3px);
transition-duration: 0.1s;
}
.textfield{
width: 500px;
height: 200px;
background: bisque;
margin-left: 150px;
margin-top: 100px;
}
</style>
<script>
b1(){
//Do some code here
}
</script>
</head>
<body>
<button id="btn1" onclick="b1();">1</button>
<p class="textfield"></p>
</body>
</html>
請告訴我如何用javascript在p標簽中寫1。當然,我也希望能夠寫出 11 或 1111。
uj5u.com熱心網友回復:
可以通過獲取元素本身來獲取元素的文本內容,如果在 的click函式內部button,可以通過this(指觸發事件的元素是按鈕),獲取它textContent,然后p通過class使用const p = document.querySelector('.textfield'), 并在里面添加按鈕的值p.textContent = buttonValue
<!DOCTYPE html>
<html>
<head>
<style>
body{
background: linear-gradient(to bottom, rgb(75,83,119), rgb(33,35,53));
}
#btn1{
background: linear-gradient(to bottom, rgb(49,87,255), rgb(78,39,255));
box-shadow: 5px 5px 10px black;
border: 0px;
border-radius: 5px;
font-size: medium;
width: 110px;
height: 40px;
text-align: center;
margin(200px,200px,200px,200px);
transition-duration: 0.1s;
}
#btn1:active{
box-shadow: 0px 0px 0px black;
transform: translateY(3px);
transition-duration: 0.1s;
}
.textfield{
width: 500px;
height: 200px;
background: bisque;
margin-left: 150px;
margin-top: 100px;
}
</style>
<script>
function b1(button){
const buttonValue = button.textContent;
const p = document.querySelector('.textfield');
p.textContent = buttonValue
}
</script>
</head>
<body>
<button id="btn1" onclick="b1(this);">1</button>
<p class="textfield"></p>
</body>
</html>
uj5u.com熱心網友回復:
如果我理解正確,您需要監聽按鈕元素的點擊。單擊按鈕時,您可以在<p>元素末尾添加一個“1”。您可以從按鈕內容中獲取此值,也可以將其添加為變數,或者像我在示例中所做的那樣,您可以在data-value屬性上定義它。
// Get the elements from the page
const button = document.querySelector('.button');
const textfield = document.querySelector('.textfield');
// Listen to click on the button
button.addEventListener('click', () => {
// Get the current value inside the textfield element
const currentText = textfield.innerHTML;
// Add the "data-value" to the end of the current text
const newText = currentText button.getAttribute('data-value');
// Replace the text on the p element with the new text
textfield.textContent = newText;
})
<button class="button" data-value="1">Click me</button>
<p class="textfield">Your p: </p>
轉載請註明出處,本文鏈接:https://www.uj5u.com/ruanti/504178.html
