以下是我的問題:我想將文本字段的值輸入到隨機引用的指定位置。但是,當我嘗試使用自己的代碼執行此操作時,JavaScript將只輸入在輸入元素括號內分配的值,並且不會更改爲在輸入字段中輸入的文本。我無法獲得JavaScript以正確訪問文本字段
在我在W3schools發現的例子中,它的工作原理與它應有的相似。當您更改輸入字段中的文本時,具有相應ID的元素中的文本將更改爲該文本。 http://www.w3schools.com/jsref/tryit.asp?filename=tryjsref_text_get
這工作:
<!DOCTYPE html>
<html>
<body>
<h3>A demonstration of how to access a Text Field</h3>
<input type="text" id="myText" value="Some text...">
<p>Click the "Try it" button to get the text in the text field.</p>
<button onclick="myFunction()">Try it</button>
<p id="demo"></p>
<script>
function myFunction() {
var x = document.getElementById("myText").value;
document.getElementById("demo").innerHTML = x;
}
</script>
</body>
</html>
但是,試圖利用這個相同的邏輯,使之與我想要做的工作的時候,這是行不通的。它僅顯示在括號內設置的輸入值。它不會更改爲顯示輸入到輸入字段中的新值。
這不起作用,我不能爲我的生活找出原因。它不會x的值更改爲在輸入區域中輸入的輸入值:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8">
<title>Quotes</title>
<script src="jquery.min.js"></script>
<script src="quotes.js"></script>
</head>
<body>
<textarea id="txtbox" style="width:600px;" readonly></textarea>
<input type="text" id="noun" value="enter noun">
<button onclick="quotes()">Next</button>
<script>
var x = document.getElementById("noun").value;
quote = [];
quote[0] = ["First part of quote " + x + " end of quote."];
quote[1] = [x + " end of quote."];
quote[2] = ["Beginning of quote " + x + "."];
quote[3] = ["First part " + x + " end of quote."];
function quotes(){
rdmQuote = Math.floor(Math.random()*quote.length);
document.getElementById("txtbox") .value=quote[rdmQuote];
}
window.onload=quotes;
</script>
</body>
</html>
*「它不會更改爲顯示輸入到輸入字段中的新值。「*你只在頁面加載時獲得文本字段的值**一次**如果你想獲得更新的文本,你需要獲得值並在每次單擊按鈕時構建引號。邏輯轉換爲'quotes' –
這可以幫助我理解錯在哪裏,但我是JavaScript新手,並且不知道如何將所有邏輯轉換爲引號。有人可以建議怎麼做? – Liberafied
他的意思是將邏輯移動到函數'quotes'中;將它放在兩個大括號之間,每次單擊按鈕時都會執行該操作 – Polyov