[英]form input does not get saved in JavaScript function. Why?
我找不到為什么這行不通。 “ document.getElementById(” number“)。value”不會在函數中“返回”。我的HTML代碼:
<!DOCTYPE html>
<html>
<head>
<link rel="stylesheet" type="text/css" href="Currency_Converter.css">
<link rel="stylesheet" href="http://code.jquery.com/ui/1.10.3/themes/smoothness/jquery-ui.css"/>
</head>
<body>
<div class="container">
<h1>Currency Converter</h1>
<form id="amount">Dollar amount  $<input id="number" type="number" name="number" onkeyup="getDollarAmount();" onchange="getDollarAmount();" placeholder="type dollar amount here" ></form>
</div>
</body>
<script type="text/javascript" src="http://code.jquery.com/jquery-1.9.1.js"></script>
<script type="text/javascript" src="http://code.jquery.com/ui/1.10.3/jquery-ui.js"></script>
<script type='text/javascript' src="Currency_Converter.js"></script>
</html>
我的JavaScript:
function getDollarAmount() {
var dollarAmount = document.getElementById("number").value;
return (dollarAmount);
}
console.log(getDollarAmount());
我的“函數getDollarAmount()”不返回放入表單的數字。 當我“ console.log(dollarAmount)”時,我得到了輸入。 當我取出“ document.getElementById(” number“)。value”並替換為數字時,(例如:5),“ getDollarAmount”函數將返回數字(5)。
顯然,問題在於“ document.getElementById(“ number”)。value“,因為該函數以其他方式工作。 我需要怎么做才能將“ document.getElementById(” number“)。value”返回給“ getDollarAmount()”?
嘗試
var dollarAmount = $("#number").val();
這里的錯誤是您要返回值,而不是將dollarAmount變量分配給輸入值屬性。
除此之外,在您鍵入要轉換的金額的相同位置返回轉換后的貨幣值的想法不是一個好習慣,而且會造成混淆。
您應該有一個輸入位置和一個顯示轉換后的值的位置。 這是更好的用戶體驗,對您也更好。
您不需要jQuery。 這是一個例子:
var el = document.getElementById("number"); el.addEventListener("keyup", function() { //You need to assign the value to a variable var dollarAmount = getDollarAmount(); }); function getDollarAmount() { return el.value; }
<input id="number" type="number" name="number" placeholder="type dollar amount here" value="0" >
希望能幫助到你。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.