DIV CSS 佈局教程網

jQuery 取值方法全解:text()、html() 與 val() 差在哪
編輯:JQuery特效代碼     

「抓元素裡的內容」和「抓輸入框的值」是兩件不同的事,很多初學者會把它們混在一起。這份範例用三顆按鈕把三種讀取方式並排展示,一次看清差異。

一、頁面與樣式

<!DOCTYPE html>
<html>
<head>
  <meta charset="utf-8">
  <title>jQuery 取值示範</title>
  <script src="js/jquery.js"></script>
<style>
body{font-family:"微軟雅黑";width:980px;margin:0 auto;text-align:center;}
.box{width:300px;height:300px;background:green;border:1px solid #e6e6e6;
     line-height:200px;position:absolute;}
button{border:none;background:green;width:125px;height:50px;line-height:50px;
       color:#fff;font-size:16px;margin-top:50px;font-family:"微軟雅黑";}
</style>
</head>
<body>
  <button id="btn1">顯示 text</button>
  <button id="btn2">顯示 html</button>
  <button id="btn3">顯示輸入內容</button>

  <p id="text">這是要顯示<b>粗體</b>的節奏</p>
  <br />
  <input id="input" value="買房子">

二、三顆按鈕的三種讀法

<script>
$(document).ready(function(){
    $("#btn1").click(function(){
        alert("Text: " + $("#text").text());
    });
    $("#btn2").click(function(){
        alert("HTML: " + $("#text").html());
    });
    $("#btn3").click(function(){
        alert("Value: " + $("#input").val());
    });
});
</script>
</body>
</html>

實際執行結果

  • .text() → 「這是要顯示的節奏」。它只取純文字,標籤本身會被剝掉。
  • .html() → 「這是要顯示<b>粗體</b>的節奏」。它連 HTML 原始碼一起帶回來。
  • .val() → 「買房子」。表單元素(input、select、textarea)的值必須用 val(),用 text() 抓不到。

寫入時也是同一組方法

這三個方法都能帶參數變成「寫入」:$("#p").text("純文字") 會把內容當成純文字處理,$("#p").html("<b>粗體</b>") 則會被瀏覽器解析成真正的標籤。因此凡是來自使用者輸入的內容,寫入時請一律走 .text(),避免 XSS。

三、觀念小結

選擇器要選對(#id 是 id 選擇器,別把 button 拼成 botton),而 alert 的組字規則就是「字串 + $(選擇器).方法()」。這兩點記牢,取值這件事就沒有難處了。

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