DIV CSS 佈局教程網

jQuery 給 div、span、a、button、radio 賦值與取值速查
編輯:JQuery特效代碼     

不同標籤的「內容」放的位置不一樣:有的放在 innerHTML,有的放在文字節點,有的則是屬性。這篇把常見元素的讀寫方式整理成一份速查表。

div:用 html()

$("#id").html("test");   // 寫入 HTML 片段
$("#id").html();         // 讀取 HTML 內容

如果內容是純文字、且可能含有使用者在 <、> 等字元,改用 text() 更安全,能避免 XSS。

a 標籤:取得連結內容

$("#id").html();      // 取得 <a> 內部的 HTML
$("#id").text();      // 取得純文字
$("#id").attr("href"); // 取得連結網址

完整可執行範例:

<script src="https://hovertree.com/ziyuan/jquery/jquery-1.12.0.min.js"></script>
<a id="hover" href="https://hovertree.com/h/bjae/jqueryhover.htm" target="_blank">
    <span style="color:red">何問起 hovertree.com</span>
</a>
<input id="hovertree" value="點我" type="button" />>

<script>
$("#hovertree").on("click", function () {
    alert($("#hover").html());
});
</script>

實際展示:

何問起 hovertree.com

span:用 text()

$('#hiddenNote').text('getSpanValues');  // 賦值
$('#hiddenNote').text();                // 取值

text() 會自動處理轉義,最適合放純文字。反過來,若 span 內需要放 HTML 標籤,才改用 html()。

button:文字寫在標籤內容裡

$('#updateBtn').text("保存");   // 把「編輯」按鈕變成「保存」

注意:如果按鈕是用 <input type="button"> 寫的,文字在 value 屬性裡,要用 val():

$('#updateBtn').val("保存");

radio:取值與賦值

取值——取得目前被選中的單選框的值:

$("input[name='radioName']:checked").val();

賦值——依 value 屬性把某個選項設為選中:

$("input[name='radioName'][value=2]").prop("checked", true);

在 jQuery 1.6 之後,checked 屬於 property,建議用 prop();若在 jQuery 3.x 使用 attr("checked", true) 可能無效。取消選中則是 .prop("checked", false)。

速查對照

div/一般容器:html() 或 text()
span、b、strong 等純文字元素:text()
連結:text() 取文字、attr("href") 取網址
<button> 標籤:text();<input type="button">:val()
radio/checkbox 選取狀態:prop("checked", ...)
表單欄位的值:val()

記住一個原則:值存在屬性裡就用 attr()/prop()/val(),存在標籤內容裡就用 text()/html(),就不容易搞混了。

XML學習教程| jQuery入門知識| AJAX入門| Dreamweaver教程| Fireworks入門知識| SEO技巧| SEO優化集錦|
Copyright © DIV+CSS佈局教程網 All Rights Reserved