JQuery检测一个文本框的内容是否被改变
为了检测输入的文本内容是否改变,我们使用JQuery的.on()方法。
.on()
这是一个由jQuery提供的内置方法,用于附加所选元素及其子元素的事件处理程序。
语法:
$(selector).on(event, childSel, data, fun, map)
参数:
- event。这个参数是必需的。它定义了要附加到所选元素的事件或命名空间。如果要提供多个事件,必须用空格分隔。
- childSel。这个参数是可选的。它定义了事件处理程序应该只附加到定义的子元素上。
- data。这个参数是可选的。它指定了要传递给函数的额外数据。
- fun。这个参数是可选的。它指定了事件发生时要运行的函数。
- map。该参数指定了一个事件地图({event: function, event: function, …}),包含一个或多个事件和函数,在事件发生时运行。
例子-1:在这个例子中,当输入的文本发生变化时,出现警告框说:‘文本内容改变了!’
<!DOCTYPE html>
<html>
<head>
<title>
JQuery |
detect a textbox's content has changed.
</title>
<script src=
"https://ajax.googleapis.com/ajax/libs/jquery/3.4.0/jquery.min.js">
</script>
</head>
<body style="text-align:center;"
id="body">
<h1 style="color:green;">
GeeksForGeeks
</h1>
<p>
Change the text of input text and
click outside of it to see.
</p>
<input id="input"
name="input"/>
<br>
<br>
<script>
$("#input").on("change", function() {
alert('Text content changed!');
});
</script>
</body>
</html>
输出:
- 点击输入框外后。
例子-2:在这个例子中,当任何一项活动发生时,警告框出现,说‘文本内容改变了!’
- 输入的文本改变了。
- 按键事件发生。
- 有东西被粘贴到了输入框中。
- 财产变化发生。
<!DOCTYPE html>
<html>
<head>
<title>
JQuery |
detect a textbox's content has changed.
</title>
<script src=
"https://ajax.googleapis.com/ajax/libs/jquery/3.4.0/jquery.min.js">
</script>
</head>
<body style="text-align:center;"
id="body">
<h1 style="color:green;">
GeeksForGeeks
</h1>
<p>
Change the text of input text
and click outside of it to see.
</p>
<input id="input"
name="input" />
<br>
<br>
<script>
$("#input").on(
"propertychange change keyup paste input", function() {
alert('Text content changed!');
});
</script>
</body>
</html>
输出:
- event发生后。