「抓元素裡的內容」和「抓輸入框的值」是兩件不同的事,很多初學者會把它們混在一起。這份範例用三顆按鈕把三種讀取方式並排展示,一次看清差異。
<!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>
這三個方法都能帶參數變成「寫入」:$("#p").text("純文字") 會把內容當成純文字處理,$("#p").html("<b>粗體</b>") 則會被瀏覽器解析成真正的標籤。因此凡是來自使用者輸入的內容,寫入時請一律走 .text(),避免 XSS。
選擇器要選對(#id 是 id 選擇器,別把 button 拼成 botton),而 alert 的組字規則就是「字串 + $(選擇器).方法()」。這兩點記牢,取值這件事就沒有難處了。