変数の送信ボタンをクリックすると、HTMLフォームのテキスト値を保存しようとしています。この値は、送信ボタンがクリックされてからもう一度blanckになるとすぐに2秒間保存されます。なぜこうなった?あなたは、(ボタンの)性質上、ページのリロードを提出クリックしているクリックイベントに値を格納
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またはlocalstorageオブジェクトを参照してください。 – jeff
@RoryMcCrossan +1 –