本文透過實例講解 jQuery 自定義添加「$」與解決「$」衝突的方法,分享給大家參考。具體分析如下:
雖然 jQuery 很強大,但無論如何都不可能滿足所有使用者的需求,而且有些需求十分小眾,也不適合放進整個 jQuery 框架中。正是因為這一點,jQuery 提供了使用者自定義添加「$」方法的能力。
程式碼如下:
程式碼如下:$.fn.disable = function() {
return this.each(function() {
if (typeof this.disabled != "undefined") this.disabled = true;
});
}
以上程式先設置 "$.fn.disable",表示為「$」添加一個 disable() 方法,其中「$.fn」是擴充 jQuery 所必須的。接著用匿名函式定義這個方法,即用 each() 把調用這個方法的每個元素的 disabled 屬性設為 true(如果該屬性存在)。
例:擴充 jQuery 的功能
程式碼如下:<script type="text/javascript">
$.fn.disable = function() {
//擴充 jQuery,表單元素統一 disable
return this.each(function() {
if (typeof this.disabled != "undefined") this.disabled = true;
});
}
$.fn.enable = function() {
//擴充 jQuery,表單元素統一 enable
return this.each(function() {
if (typeof this.disabled != "undefined") this.disabled = false;
});
}
function SwapInput(oName, oButton) {
if (oButton.value == "Disable") {
//如果按鈕的值為 Disable,則調用 disable() 方法
$("input[name=" + oName + "]").disable();
oButton.value = "Enable";
} else {
//如果按鈕的值為 Enable,則調用 enable() 方法
$("input[name=" + oName + "]").enable();
oButton.value = "Disable"; //然後設置按鈕的值為 Disable
}
}
</script>
<form method="post" name="myForm1" action="addInfo.aspx">
<p>
<label for="name">請輸入您的姓名:</label>
<br>
<input type="text" name="name" id="name" class="txt">
</p>
<p>
<label for="passwd">請輸入您的密碼:</label>
<br>
<input type="password" name="passwd" id="passwd" class="txt">
</p>
<p>
<label for="color">請選擇你最喜歡的顏色:</label>
<br>
<select name="color" id="color">
<option value="red">紅</option>
<option value="green">綠</option>
<option value="blue">藍</option>
<option value="yellow">黃</option>
<option value="cyan">青</option>
<option value="purple">紫</option>
</select>
</p>
<p>請選擇你的性別:
<br>
<input type="radio" name="sex" id="male" value="male">
<label for="male">男</label>
<br>
<input type="radio" name="sex" id="female" value="female">
<label for="female">女</label>
</p>
<p>你喜歡做些什麼:
<input type="button" name="btnSwap" id="btnSwap" value="Disable" class="btn" onclick="SwapInput('hobby',this)">
<br>
<input type="checkbox" name="hobby" id="book" value="book">
<label for="book">看書</label>
<input type="checkbox" name="hobby" id="net" value="net">
<label for="net">上網</label>
<input type="checkbox" name="hobby" id="sleep" value="sleep">
<label for="sleep">睡覺</label>
</p>
<p>
<label for="comments">我要留言:</label>
<br>
<textarea name="comments" id="comments" cols="30" rows="4"></textarea>
</p>
<p>
<input type="submit" name="btnSubmit" id="btnSubmit" value="Submit" class="btn">
<input type="reset" name="btnReset" id="btnReset" value="Reset" class="btn">
</p>
</form>
方法 SwapInput(oName, oButton) 會根據按鈕的值進行判斷:如果是 disabled,就調用 disable() 把元素設為不可用,同時把按鈕的值改成 enable;反之則調用 enable() 方法。
與前面情況類似,儘管 jQuery 非常強大,但有時開發者會同時使用多個框架,這時就要小心,因為其他框架也可能使用了「$」,從而發生衝突。jQuery 同樣提供了 noConflict() 方法來解決「$」衝突的問題。
程式碼如下:jQuery.noConflict();
以上程式便能讓「$」按照其他 JavaScript 框架的方式運作,此後 jQuery 中便不能再使用「$」,而必須使用「jQuery」,例如 $("h2 a") 必須寫成 jQuery("h2 a")。
希望本文所述對大家的 jQuery 程式設計有所幫助。