当单击变量上的提交按钮时,我试图存储 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>
最佳答案
默认情况下,按表单
内的按钮会提交表单。因此,您的页面将重新加载,并且您会丢失客户端变量的所有状态。
为了防止这种情况,您可以:
- 通过在监听器中传递的事件对象上调用
e.preventDefault()
来阻止提交 - 使用另一种机制(例如 cookies)将变量从一个页面加载传递到另一个页面
示例preventDefault
var userSearch = "";
$(document).ready(function() {
$("#buttonA").click(function(e) {
e.preventDefault();
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" type="button">Submit</button>
</form>
</div>
<div id="resultsBox"></div>
</div>
</body>
关于javascript - 在点击事件上存储值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/38745931/