做 B/S 開發一年多卻沒好好讀過 jQuery,趁這幾天來補一補。以下兩個小練習很基本,但剛好把最常見的兩種選擇器都涵蓋了。
用標籤選擇器一次選中所有同類元素並隱藏:
<!DOCTYPE html>
<html xmlns="https://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title>按鈕點擊消失文本</title>
<script src="jquery.js"></script>
<script type="text/javascript" language="javascript">
/* 等待文件就緒 */
$(document).ready(function () {
/* 為 button 標籤掛上點擊事件 */
$("button").click(function () {
/* 把所有 p 標籤隱藏 */
$("p").hide();
});
});
</script>
</head>
<body>
<h2>This is a heading</h2>
<p>This is a paragraph</p>
<p>This is a another paragraph</p>
<button type="button">Click me</button>
<input type="button" value="Click me" />
</body>
</html>
這裡有個值得留意的細節:$("button") 只選到 <button> 標籤,不會選到 <input type="button">——兩者雖然視覺上都是按鈕,但在選擇器眼中是不同元素。所以實際操作時只有那顆 button 有反應。另外 $("p") 會一次隱藏全部段落,這正是前面提到的隱式遍歷。
若只想隱藏單一元素,用 id 選擇器加上 # 即可:
<!DOCTYPE html>
<html xmlns="https://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title>通過ID隱藏控件</title>
<script src="jquery.js"></script>
<script type="text/javascript" language="javascript">
$(document).ready(function () {
$("button").click(function () {
$("#test").hide();
});
});
</script>
</head>
<body>
<h2>This is a heading</h2>
<p>This is a paragraph</p>
<p id="test">This is another paragraph</p>
<button type="button">隱藏控件 id 為 test 的 p 標籤</button>
</body>
</html>
這次只有帶 id="test" 的那段文字會消失,其餘保持不變。
標籤選擇器 $("p") 選一整類元素,id 選擇器 $("#test") 精準選一個。而 $(document).ready() 確保 DOM 就緒後才執行動作,hide() 則是最基本的隱藏方法(等同設定 display:none)。這三個觀念是所有 jQuery 應用的起點。