利用jQuery扩展接口为jQuery框架定义了两个自定义函数,然后调用这两个函数

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">

<html xmlns="http://www.w3.org/1999/xhtml" xml:>

<head>

<meta http-equiv="Content-Type" content="text/html;charset=UTF-8">

<title>利用jQuery扩展接口为jQuery框架定义了两个自定义函数,然后调用这两个函数</title>

<script type="text/javascript" src="jquery-1.11.3.min.js"></script>

<script>

jQuery.fn.extend({ //调用扩展函数

check:function(){ //为表单元素扩展check函数,选中单选按钮或者复选框

return this.each(function(){this.checked=true;});

},

uncheck:function(){ //为表单元素扩展check函数,取消选中单选按钮或者复选框

return this.each(function(){this.checked=false;});

}

});

$(function(){ //应用扩展函数

$("input[type=checkbox]").check();

$("input[type=radio]").uncheck();

});

</script>

</head>

<body>

<input type="radio" />

<input type="radio" checked="checked" />

<input type="checkbox" />

<input type="checkbox" checked="checked" />

</body>

</html>

在上面代码中,jQuery.fn.extend 其实是 jQuery.extend = jQuery.fn.extend = jQuery.prototype.extend。可能读者会想,如果使用jQuery.fn.extend增加扩展函数,在调用时应该是$(xxx).extend.xxxx(),而不应该是类似于上面示例代码所调用的$(xxx).xxxx(),当然,肯定是有代码在处理后才能这么调用。

在扩展函数extend()中以对象直接量的形式包含了两个自定义方法:check()和uncheck()。check()方法能够为jQuery匹配的每个表单元素定义选中状态,uncheck()方法能够为jQuery匹配的每个表单元素定义未选中状态。