[英]How to set textbox input to a variable
我目前剛剛接觸 HTML 的 JavaScript。 我已經使用 HTML 和 CSS 有一段時間了,但我最近才開始使用 Python,所以現在我覺得我會更有能力/能夠理解 JavaScript。
我目前正在研究我的一個想法,一個幸運餅干制造商。 用戶將文本輸入到文本框輸入中。 這存儲在一個變量中。 當用戶單擊確定時,它會從文本框中獲取文本,並將其設置為該變量。 然后,它切換頁面,從腳本中獲取變量,並將一個段落設置為該變量的文本值。
但是,我的問題是,該段落不會顯示文本。
這是我的代碼:
var fortune = null;
function dispTxt() {
var txt = document.getElementById('textbox').value;
var hid = document.getElementById('conftxt');
if (txt.length > 0) {
//hid.style.display = 'block';
document.getElementById("conftxt").style.opacity = 1;
document.getElementById("textbox").style.color = "#ffffff";
} else {
//hid.style.display = 'none';
document.getElementById("conftxt").style.opacity = 0;
//document.getElementById("textbox").style.color = "#000000";
}
document.getElementById("txt").addEventListener("onkeyup", function() {
dispTxt();
})
};
function confirm() {
//Get the text that is inputted by the user.
fortune = document.getElementById("conftxt").value;
window.location = "fortune.html";
window.alert(fortune);
}
function setFortune() {
document.getElementById('fortunetext').value = fortune;
}
另外,如果有人對我應該如何制作幸運餅干有任何建議,請告訴我。 我基本上只是希望它是這樣的,一旦你確認了運勢所說的,就會出現幸運餅干,你可以點擊它,打開它,它就會顯示運勢。
謝謝!
你說fortune = document.getElementById("conftxt").value;
, 但 #conftxt 是按鈕元素。
fortune = document.getElementById("textbox").value;
會做
但由於頁面刷新/重定向到fortune.html變量fortune
再次被清除。
您有兩個選擇:
使用一個 HTML 頁面,因此您不使用重定向
將變量存儲在localStorage或sessionStorage 中
將值傳遞到 URL 參數中。 鏈接:將變量傳遞給 URL和從 URl 獲取傳遞的變量
我推薦1。
您無法獲得價值,因為您獲得了錯誤的元素
function confirm () {
fortune = document.getElementById("conftxt").value;
...
}
應該
function confirm () {
fortune = document.getElementById("textbox").value;
...
}
此外,您正在不同頁面之間導航,因此,您需要傳遞此值
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.