如何在JQuery中检测隐藏输入字段的数值变化
在<input> type="hidden "
的元素中,jQuery的change()方法不会被自动触发。只有当用户自己改变字段的值时,才会自动触发change()方法,而不是开发人员。当开发者改变隐藏字段的值时,他也必须触发改变。
有两种可能的方法来检测隐藏的输入字段上的数值变化。
- 通过使用bind()方法
- 通过使用change()方法
下面的例子将说明检测隐藏字段中数值变化的两种方法。
例子1:下面的例子使用jQuery内置的bind()方法。
<!DOCTYPE html>
<html>
<head>
<title>
By using bind() method detecting change
of value in the hidden field
</title>
<script src="https://code.jquery.com/jquery-3.4.1.js"
integrity="sha256-WpOohJOqMqqyKL9FccASB9O0KwACQJpFTUBLTYOVvVU="
crossorigin="anonymous">
</script>
</head>
<body style="text-align:center;">
<h1 style="color:green;">
GeeksforGeeks
</h1>
<h3>By using bind() method</h3>
<form>
<input type="hidden" value="" id="hidField">
<button type="button" id="changeValue">
Click to change value
</button>
</form>
<script>
(document).ready(function() {
alert("Value of hidden field before updating: "
+("#hidField").val());
("#changeValue").click(function() {
("#hidField").val(10).trigger("change");
});
("input[type='hidden']").bind("change", function() {
alert("Value of hidden field after updating: "
+(this).val());
});
})
</script>
</body>
</html>
输出:
例子2:下面的例子使用jQuery内置的change()方法。
<!DOCTYPE html>
<html>
<head>
<title>
By using change() method detecting change
of value in the hidden field
</title>
<script src="https://code.jquery.com/jquery-3.4.1.js"
integrity="sha256-WpOohJOqMqqyKL9FccASB9O0KwACQJpFTUBLTYOVvVU="
crossorigin="anonymous"></script>
</head>
<body style="text-align:center;">
<h1 style="color:green;">
GeeksforGeeks
</h1>
<h3>By using change() method</h3>
<form>
<input type="hidden" value="" id="hidField">
<br>
<button type="button" id="changeValue">
Click to change value
</button>
</form>
<script>
(document).ready(function() {
alert("Value of hidden field before updating: "
+("#hidField").val());
("#changeValue").click(function() {
("#hidField").val(101).trigger("change");
});
("#hidField").change(function() {
alert("Value of hidden field after updating: "
+("#hidField").val());
});
})
</script>
</body>
</html>
输出:
jQuery是一个开源的JavaScript库,它简化了HTML/CSS文档之间的交互,它以其 “少写多做 “的理念而广为人知。