html()、text()、val() 這三個方法長得很像,用途卻不能互換。以下用實例把差別講清楚。
<script type="text/javascript">
$(function(){
// 取得 <p> 的 HTML 內容
$("input:eq(0)").click(function(){
alert($("p").html());
});
// 取得 <p> 的純文字
$("input:eq(1)").click(function(){
alert($("p").text());
});
// 設定 HTML(標籤會被解析)
$("input:eq(2)").click(function(){
$("p").html("<strong>你最喜歡的水果是?</strong>");
});
// 設定文字(標籤會被當成字元顯示)
$("input:eq(3)").click(function(){
$("p").text("你最喜歡的水果是?");
});
// 同樣的字串,用 text() 設定
$("input:eq(4)").click(function(){
$("p").text("<strong>你最喜歡的水果是?</strong>");
});
// 取得按鈕的 value
$("input:eq(5)").click(function(){
alert($(this).val());
});
// 設定按鈕的 value
$("input:eq(6)").click(function(){
$(this).val("我被點擊了!");
});
});
</script>
比較 eq(2) 與 eq(4) 就能看出關鍵:同一個字串,用 html() 設定會產生出粗體,用 text() 設定則會把角括號原樣印在畫面上。凡是內容可能來自使用者輸入,一律用 text(),這是防 XSS 的基本動作。
常見需求是「提示文字在聚焦時消失、失焦時若為空則回來」。直接比對字串的做法:
<script type="text/javascript">
$(function(){
$("#address").focus(function(){ // 取得焦點
var txt_value = $(this).val();
if (txt_value == "請輸入郵箱地址") {
$(this).val("");
}
});
$("#address").blur(function(){ // 失去焦點
var txt_value = $(this).val();
if (txt_value == "") {
$(this).val("請輸入郵箱地址");
}
});
$("#password").focus(function(){
var txt_value = $(this).val();
if (txt_value == "請輸入郵箱密碼") {
$(this).val("");
}
});
$("#password").blur(function(){
var txt_value = $(this).val();
if (txt_value == "") {
$(this).val("請輸入郵箱密碼");
}
});
});
</script>
把提示文字寫進 value 有個問題:使用者真的想輸入「請輸入郵箱地址」這幾個字時,就無法區分了。比較好的寫法是拿 defaultValue 當基準,或直接改用 placeholder:
$("#address").focus(function(){
if ($(this).val() == this.defaultValue) { $(this).val(""); }
}).blur(function(){
if ($(this).val() == "") { $(this).val(this.defaultValue); }
});
// 現代做法,一行取代全部
<input id="address" type="text" placeholder="請輸入郵箱地址" />
placeholder 由瀏覽器原生處理,聚焦時自動消失,也不會混進真正的送出值,是現階段的正確選擇。
<script type="text/javascript">
$(function(){
// 單選下拉框
$("input:eq(0)").click(function(){
$("#single").val("2");
});
// 多選下拉框:傳陣列
$("input:eq(1)").click(function(){
$("#multiple").val(["選擇2號", "選擇3號"]);
});
// 核取方塊與單選鈕
$("input:eq(2)").click(function(){
$(":checkbox").val(["check2","check3"]);
$(":radio").val(["radio2"]);
});
});
</script>
另一種等價寫法是操作 selected/checked 屬性:
$("#single option").removeAttr("selected");
$("#single option:eq(1)").attr("selected", true);
$("#multiple option").removeAttr("selected");
$("#multiple option:eq(2)").attr("selected", true);
$("#multiple option:eq(3)").attr("selected", true);
$(":checkbox").removeAttr("checked");
$(":radio").removeAttr("checked");
$(":checkbox[value=check2]").attr("checked", true);
$("[value=check3]:checkbox").attr("checked", true);
$("[value=radio2]:radio").attr("checked", true);
補充兩點::checkbox 這種寫法是「屬性為 checkbox」的選項。另外自 jQuery 1.6 起,checked/selected 這類「目前狀態」應該用 prop() 而非 attr(),兩者混用會出現抓不到值的怪現象;在 1.9 之後 .attr("checked") 已不再回報當前勾選狀態。新專案請統一寫成 $(x).prop("checked", true)。