[英]Making a Button Text Based on Variable
我正在制作一個不公平的骰子滾輪,並且我有一個帶有此代碼的按鈕:
<button type="button" id="roll-button">Roll the Dice</button>
該按鈕擲骰子,但我希望站點查看器能夠更改此按鈕的內容。 我不知道該怎么做。 它是否與 JavaScript 中的變量有關?
主要問題:如何讓用戶能夠使用表單元素更改文本?
第一次從文檔中獲取元素,然后將其文本內容屬性更改為變量文本。
如何使該人能夠使用表單元素更改文本?
假設這是一個文本輸入,您必須從輸入中獲取值,然后更改按鈕的文本。
為該演示添加了一個額外的文本輸入字段,其 id 為“text-field”。
var textInput = document.getElementById("text-field").value; //gets text-field value
var button = document.getElementById("roll-button"); //gets the button element
button.innerHTML = textInput; //changes the value to what the text input is
你想這樣嗎?
下面的代碼是創建button
標簽。 我還設置button
標簽屬性id
和type
。
HTML
...
<div id="root">
</div>
Javascript
<script>
var buttonText = 'Roll the Dice';
var button = document.createElement('button');
button.textContent = buttonText;
button.setAttribute('id', 'roll-button');
button.setAttribute('type', 'button');
document.getElementById('root').appendChild(button);
</script>
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.