3 回答

TA貢獻1811條經驗 獲得超6個贊
var t = document.getElementById("text").value
function func() {
document.getElementById("ascii").value = t;
}
目前您的var t = document.getElementById("text").value代碼只會執行一次。第一次,該值將為“”,因為 textArea 第一次為空。
您需要將其移動到內部,func()以便每次func()執行時都會獲得最新值
function func() {
var t = document.getElementById("text").value
document.getElementById("ascii").value = t;
}

TA貢獻1812條經驗 獲得超5個贊
將 var 聲明放入函數中:
function func() {
var t = document.getElementById("text").value
document.getElementById("ascii").value = t;
}

TA貢獻2039條經驗 獲得超8個贊
您僅聲明一次值,t而無法在單擊按鈕時查找并獲取該值。任何您想要多次執行的任務都必須在函數或重復出現的表達式中,等等。以下演示僅在函數外部聲明一個變量,其余變量在函數內部 - 詳細信息在演示中注釋。
順便說一句,如果您正在處理表單字段(例如輸入、輸出、文本區域等),那么您有必要扭曲表單中的所有內容并使用表單來管理所有表單字段。
演示
// Reference the form
const editor = document.forms.editor;
// Register the form to the input event
editor.oninput = edit;
// pass the event object
function edit(event) {
/*
= 'this' is the form
= `field` is a NodeList of inputs, buttons, textareas,
etc
*/
const field = this.elements;
/*
= event.target is the tag the user interacted with
In this case it would be textarea#in
*/
const input = event.target;
// Reference textarea#out
const output = field.out;
/*
= if the event.target is textarea#in...
= Set the value of textarea#out to the value of
textarea#in
*/
if (input.id === 'in') {
output.value = input.value;
}
}
<form id='editor'>
<textarea id='in'></textarea>
<textarea id='out'></textarea>
</form>
- 3 回答
- 0 關注
- 198 瀏覽
添加回答
舉報