id 選擇器是 jQuery 中用來精準定位單個元素的方式。本文用一個簡潔的例子,演示如何用 hide() 隱藏某個指定 id 的元素。
關鍵選擇器是 $("#test"),它精準命中 id 為 test 的元素:
<!DOCTYPE html> <html> <head> <script src="js/jquery.min.js"> </script> <script> $(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>Click me</button> </body> </html>
點擊按鈕後,只有 id 為 test 的那段文字被隱藏,其餘元素不受影響。當你需要精準操作頁面上唯一的某個元素時,id 選擇器配合 hide() 是最直接的選擇。