.change( handler(eventObject) ) 函数的使用
这个函数的第一种用法是 .bind('change', handler) 的快捷方式,第二种用法是 .bind('change') 的快捷方式。
一个元素的值改变的时候将触发change事件。此事件仅限于<input>元素,<textarea>框和<select>元素。对于选择框,复选框和单选按钮,当用户用鼠标作出选择,该事件立即触发,但对于其他类型元素,该事件触发将推迟到元素失去焦点。
$("input:[name=agree]").change(function(){
chooseAll();
});
然后chooseAll()方法里在判断选的是全选还是全不选,然后根据判断结果循环需要选择的对象,判断该对象的值时候与判断结果的值是否相等,若相等则checked=true,否则就不做处理。
示例代码:
<html>
<head>
<style>
div { color:red; }
</style>
<script type="text/javascript" src="jquery-1.6.4.js"></script>
</head>
<body>
<div>
<input type="radio" name="agree" value="true">全选</input><input type="radio" name="agree" value="false">全不选</input>
</div>
<form id="first">
<div><input type="radio" name="agree1" value="true">同意</input><input type="radio" name="agree1" value="false">不同意</input></div>
<div><input type="radio" name="agree2" value="true">同意</input><input type="radio" name="agree2" value="false">不同意</input></div>
<div><input type="radio" name="agree3" value="true">同意</input><input type="radio" name="agree3" value="false">不同意</input></div>
<div><input type="radio" name="agree4" value="true">同意</input><input type="radio" name="agree4" value="false">不同意</input></div>
</form>
<select name="sweets" multiple="multiple">
<option>Chocolate</option>
<option selected="selected">Candy</option>
<option>Taffy</option>
<option selected="selected">Caramel</option>
<option>Fudge</option>
<option>Cookie</option>
</select>
<div id="test"></div>
<script>
$("input:[name=agree]").change(function(){
chooseAll();
});
function chooseAll(){
var agreeFlag = $("input:[name=agree]:radio:checked").val();
if (agreeFlag == "true")
{
$("#first input:radio").each(function(){
var isAgree = $(this).attr("value");
if (isAgree == "true")
{
$(this).attr("checked",true);
}
});
}else if (agreeFlag == "false")
{
$("#first input:radio").each(function(){
var isAgree = $(this).attr("value");
if (isAgree == "false")
{
$(this).attr("checked",true);
}
});
}
}
$("select").change(function () {
var str = "";
$("select option:selected").each(function () {
str += $(this).text() + " ";
});
$("#test").text(str);
})
.change();
</script>
</body>
</html>运行结果:

本文详细介绍了如何使用JavaScript的change方法在HTML表单中实现全选和全不选功能,包括利用全选全不选按钮与radio输入框之间的联动,以及在选择框变化时实时更新展示内容的实现过程。
762





