Jquery change()
jQuery change()
当元素的值更改时,发生jQuery change事件。它仅适用于表单字段。当发生change事件时,change()方法将附加一个函数来运行。
注意: 此事件仅限于<input>元素,<textarea>框和<select>元素。
对于选择框,复选框和单选按钮: 当用户使用鼠标进行选择时,会立即触发该事件。
对于其他元素类型: 该事件在字段失去焦点时发生。
语法:
它触发选定元素的更改事件。
$(selector).change(function)
它为change事件添加了一个函数。
jQuery change()事件的参数
参数 |
说明 |
function |
这是一个可选参数。用于指定所选元素发生更改事件时要运行的功能。 |
jQuery change()事件的示例
让我们以一个示例来演示jQuery change()事件。
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8">
<title>change demo</title>
<style>
div {
color: red;
}
</style>
<script src="https://code.jquery.com/jquery-1.10.2.js"></script>
</head>
<body>
<select id="se" name="actors" >
<option>Uthappa</option>
<option selected="selected">Kattapa</option>
<option>Veerappa</option>
<option>Bahubali</option>
<option>Bhallal Dev</option>
<option>Awantika</option>
</select>
<div id="loc"></div>
<script>
$("select") .change(function() {
document.getElementById("loc").innerHTML="您选择了: "+document.getElementById("se").value;
});
</script>
</body>
</html>
输出:
让我们看一下jQuery change事件的另一个示例,在该示例中,我们提供了使用ctrl键选择多个数据的选项。
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8">
<title>change demo</title>
<style>
div {
color: red;
}
</style>
<script src="https://code.jquery.com/jquery-1.10.2.js"></script>
</head>
<body>
<select name="Employees" multiple="multiple">
<option>Uthappa</option>
<option selected="selected">Kattapa</option>
<option>Veerappa</option>
<option selected="selected">Bahubali</option>
<option>Bhallal Dev</option>
<option>Awantika</option>
</select>
<div></div>
<script>
$("select")
.change(function() {
var str = "";
$("select option:selected").each(function() {
str += $( this ).text() + " ";
});
$("div").text( str );
})
.change();
</script>
</body>
</html>
输出: