3 回答

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

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

TA貢獻2039條經(jīng)驗 獲得超8個贊
您僅聲明一次值,t而無法在單擊按鈕時查找并獲取該值。任何您想要多次執(zhí)行的任務(wù)都必須在函數(shù)或重復出現(xiàn)的表達式中,等等。以下演示僅在函數(shù)外部聲明一個變量,其余變量在函數(shù)內(nèi)部 - 詳細信息在演示中注釋。
順便說一句,如果您正在處理表單字段(例如輸入、輸出、文本區(qū)域等),那么您有必要扭曲表單中的所有內(nèi)容并使用表單來管理所有表單字段。
演示
// 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 關(guān)注
- 191 瀏覽
添加回答
舉報