我試圖在單擊變量上的提交按鈕時存儲html表單的文本值。當點擊提交按鈕後,該值立即被存儲一秒,然後再次變爲空白。這是爲什麼發生?單擊事件時的存儲值
var userSearch = "";
$(document).ready(function() {
$("#buttonA").click(function() {
userSearch = document.getElementById("userSearch").value;
console.log(userSearch);
});
console.log(userSearch);
});
<!DOCTYPE>
<head>
<link rel="stylesheet" href="stylesheet.css">
<link href="https://fonts.googleapis.com/css?family=Open+Sans" rel="stylesheet">
<link href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.6/css/bootstrap.min.css" rel="stylesheet" integrity="sha384-1q8mTJOASx8j1Au+a5WDVnPi2lkFfwwEAa8hDDdjZlpLegxhjVME1fgjWPGmkzs7" crossorigin="anonymous">
<script src="https://use.fontawesome.com/ca5f7b6f9a.js"></script>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.0/jquery.min.js"></script>
<script src="script.js"></script>
</head>
<body>
<div class="container text-center">
<a href="https://en.wikipedia.org/wiki/Special:Random"> Random article</a>
<div id="searchBox">
<form>
<input type="text" id="userSearch" name="userSearch">
<button id="buttonA">Submit</button>
</form>
</div>
<div id="resultsBox"></div>
</div>
</body>
您在提交由點擊頁面重載 – Maxx
形式當你點擊提交整個頁面被重新加載從而失去了以前的值。如果您需要保留該值,請查看Cookie或本地存儲對象。 – jeff
@RoryMcCrossan +1 –