jQuery 的 hide() 方法是最常用的元素隱藏手段之一。本文用一個簡潔的例子,演示如何讓按鈕在被點擊後把自己隱藏起來,重點在於理解 this 的用法。
關鍵寫法是 $(this).hide(),其中 this 指向當前被點擊的元素:
<!DOCTYPE html> <html> <head> <script src="js/jquery.min.js"> </script> <script> $(document).ready(function(){ $("button").click(function(){ $(this).hide(); }); }); </script> </head> <body> <h2>This is a heading</h2> <p>This is a paragraph.</p> <p>This is another paragraph.</p> <button>Click me</button> </body> </html>
點擊按鈕後,$(this) 精準定位到被點擊的按鈕本身並將其隱藏。這種"隱藏自己"的寫法在刪除列表項、關閉提示框等交互中非常實用。