元素的顯示與隱藏是網頁互動最基礎的效果之一。除了原生 JavaScript 直接操作 style.display,jQuery 提供的 hide() 與 show() 更加簡潔直觀。本文用一個小範例示範兩種寫法的對比。
下面的程式同時準備了原生寫法與 jQuery 寫法的按鈕,點擊即可隱藏或顯示文字框:
<html xmlns="https://www.w3.org/1999/xhtml">
<head runat="server">
<title></title>
<script type="text/jscript" src="jquery/jquery-1.10.2.js"></script>
<script type="text/javascript">
$(document).ready(function () {
$("#but1").click(function () { $("#tex1").hide(); });
});
$(document).ready(function () {
$("#but2").click(function () { $("#tex1").show(); });
});
</script>
</head>
<body>
<form id="form1" runat="server">
<div>
<input type="button" value="客戶端隱藏" onclick="document.getElementById('tex1').style.display='none'" />
<input type="button" value="客戶端顯示" onclick="document.getElementById('tex1').style.display='inline'" />
<input type="button" value="$客戶端隱藏" id="but1" />
<input type="button" value="$客戶端顯示" id="but2" />
<input type="text" id="tex1" />
</div>
</form>
</body>
</html>
對照之下可發現,jQuery 只要一行 $("#tex1").hide() 就能完成同樣的事,程式碼更乾淨、可讀性也更高。