我需要你的帮助,
我是 jQuery 的新手,我不确定我将如何获取在任一 3 个文本框中输入的先前文本。
这是 JavaScript 和 HTML 代码:
<!DOCTYPE html>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8">
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.3/jquery.min.js"></script>
<script type="text/javascript">
window.onload = function() {
$('#one, #two, #three').change(function(e) {
alert(e.target.value)
});
}
</script>
</head>
<body>
<input type="text" id="one">
<input type="text" id="two">
<input type="text" id="three">
</body>
</html>
最佳答案
一种解决方案是将值缓存在一个对象中。这是我能想到的最干净的方式。
var values = {};
$('#one, #two, #three').change(function(e) {
// Get the text from cache, dynamically
var prevText = values[e.target.id] || "";
// Show something to the user
alert("Modified: " + e.target.value + " | Old: " + prevText);
// Update the text in cache
values[e.target.id] = e.target.value;
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<input type="text" id="one">
<input type="text" id="two">
<input type="text" id="three">
或者,您可以直接将旧值存储在元素对象中,但我不建议以这种方式污染它(除非您小心操作):
$('#one, #two, #three').change(function(e) {
var el = e.target;
alert("Modified: " + e.target.value + " | Old: " + (el._old_value || ""));
el._old_value = e.target.value;
});
关于javascript - 如何使用 jQuery 获取在输入框中输入的上一个文本值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30899096/