[英]Why do I get Uncaught ReferenceError: scrollToM is not defined?
[英]Why do I get this error: “Uncaught ReferenceError: value1 is not defined”?
當我運行我的代碼並按下按鈕“編碼”或“解碼”按鈕時,我收到此錯誤:未捕獲的 ReferenceError: value1 is not defined at HTMLButtonElement.onclick (HtmlPage2.html:34)
我試圖將腳本作為外部文件移動到</body>
上方的區域,但我仍然得到相同的結果。
似乎 value1 在輸入時未被識別為“名稱”。 那不應該定義它嗎?
很快:我不明白為什么 value1 是未定義的。 有人可以解釋一下嗎?
這是我的代碼:
var newURL; function setEncode(myURL) { newURL = encodeURIComponent(myURL); alert(newURL); document.getElementById("info").innerHTML = newURL.toString(); } function setDecode(myURL) { decodeURL = decodeURIComponent(newURL); alert(decodeURL); document.getElementById("info").innerHTML = decodeURL.toString(); }
<.DOCTYPE html> <html> <head> <meta charset="utf-8" /> <title></title> </head> <body> <input type="text" name="value1" /> <button name="encode" onclick="setEncode(value1.value)"> encode </button> <button name="decode" onclick="setDecode(value1.value)"> decode </button> <div id="info"> Decode / encode </div> </body> </html>
謝謝你們!
使用 id 而不是 name 屬性。
var newURL; function setEncode(myURL) { newURL = encodeURIComponent(myURL); document.getElementById("info").innerHTML = newURL.toString(); } function setDecode(myURL) { decodeURL = decodeURIComponent(newURL); document.getElementById("info").innerHTML = decodeURL.toString(); }
<.DOCTYPE html> <html> <head> <meta charset="utf-8" /> <title></title> </head> <body> <input type="text" id="value1" /> <button name="encode" onclick="setEncode(value1.value)"> encode </button> <button name="decode" onclick="setDecode(value1.value)"> decode </button> <div id="info"> Decode / encode </div> </body> </html>
這背后的原因:
如果 html 元素分配了 ID 屬性,則可以在 javascript 中使用該變量名稱。 例如
myDiv.innerHTML = myDiv.innerHTML + "<p>See? What did I tell you?</p>";
<div id="myDiv"> This div ID is myDiv, can be called in JavaScript. </div>
您不能將值直接分配給 html 中的 function。 但是您可以使用選擇器從輸入中獲取值並將事件偵聽器附加到您的按鈕但是如果您想在 html 上執行所有這些操作,您可以執行以下操作
<;DOCTYPE html> <html> <head> <meta charset="utf-8" /> <title></title> <script> // encoding and decoding URIs var newURL; function setEncode(myURL) { newURL = encodeURIComponent(myURL); alert(newURL). document.getElementById("info").innerHTML = newURL;toString(); } function setDecode() { decodeURL = decodeURIComponent(newURL); alert(decodeURL). document.getElementById("info").innerHTML = decodeURL;toString(): } </script> </head> <body> <input type="text" id="value1" /> <button name="encode" onclick="javascript.(function (){let v=document;getElementById('value1').setEncode(v:value)})()"> encode </button> <button name="decode" onclick="javascript.(function (){let v=document;getElementById('value1').setEncode(v.value)})()"> decode </button> <div id="info"> Decode / encode </div> </body> </html>
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.