jQuery自定义添加"$"与解决"$"冲突的方法
本文实例讲述了jQuery自定义添加"$"与解决"$"冲突的方法。分享给大家供大家参考。具体分析如下:
1.自定义添加$
虽然jQuery很强大,但无论如何,jQuery都不可能满足所有用户的需求,而且有一些需求十分小众,也不适合放到整个jQuery框架中,正是因为这一点,jQuery提供了用户自定义添加“$”的方法。
代码如下:
$.fn.disable=function(){ returnthis.each(function(){ if(typeofthis.disabled!="undefined")this.disable=true; }); }
以上代码首先设置"$.fn.disable",表明“$”添加一个方法disable(),其中“$.fn”是扩展jQuery所必须的。
然后利用匿名函数定义这个方法,即用each()将调运这个方法的每个元素disabled属性均设置为true.(如果该属性存在)
例:扩展jquery的功能
<scripttype="text/javascript"> $.fn.disable=function(){ //扩展jQuery,表单元素统一disable returnthis.each(function(){ if(typeofthis.disabled!="undefined")this.disabled=true; }); } $.fn.enable=function(){ //扩展jQuery,表单元素统一enable returnthis.each(function(){ if(typeofthis.disabled!="undefined")this.disabled=false; }); }
functionSwapInput(oName,oButton){ if(oButton.value=="Disable"){ //如果按钮的值为Disable,则调用disable()方法 $("input[name="+oName+"]").disable(); oButton.value="Enable"; }else{ //如果按钮的值为Eable,则调用enable()方法 $("input[name="+oName+"]").enable(); oButton.value="Disable";//然后设置按钮的值为Disable } } </script> <formmethod="post"name="myForm1"action="addInfo.aspx"> <p> <labelfor="name">请输入您的姓名:</label> <br> <inputtype="text"name="name"id="name"class="txt"> </p> <p> <labelfor="passwd">请输入您的密码:</label> <br> <inputtype="password"name="passwd"id="passwd"class="txt"> </p> <p> <labelfor="color">请选择你最喜欢的颜色:</label> <br> <selectname="color"id="color"> <optionvalue="red">红</option> <optionvalue="green">绿</option> <optionvalue="blue">蓝</option> <optionvalue="yellow">黄</option> <optionvalue="cyan">青</option> <optionvalue="purple">紫</option> </select> </p> <p>请选择你的性别: <br> <inputtype="radio"name="sex"id="male"value="male"> <labelfor="male">男</label> <br> <inputtype="radio"name="sex"id="female"value="female"> <labelfor="female">女</label> </p> <p>你喜欢做些什么: <inputtype="button"name="btnSwap"id="btnSwap"value="Disable"class="btn"onclick="SwapInput('hobby',this)"> <br> <inputtype="checkbox"name="hobby"id="book"value="book"> <labelfor="book">看书</label> <inputtype="checkbox"name="hobby"id="net"value="net"> <labelfor="net">上网</label> <inputtype="checkbox"name="hobby"id="sleep"value="sleep"> <labelfor="sleep">睡觉</label> </p> <p> <labelfor="comments">我要留言:</label> <br> <textareaname="comments"id="comments"cols="30"rows="4"></textarea> </p> <p> <inputtype="submit"name="btnSubmit"id="btnSubmit"value="Submit"class="btn"> <inputtype="reset"name="btnReset"id="btnReset"value="Reset"class="btn"> </p> </form>