要做一個簡單的運算符輸入面板:點擊哪個按鈕,就把對應符號追加到 textarea 裡。這個需求很基礎,但裡面有幾個 jQuery 用法值得留意。
<%@ page language="java" contentType="text/html; charset=gbk"
pageEncoding="gbk"%>
<%@ include file="/pages/common/taglibs.jsp"%>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN"
"https://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<script type="text/javascript" src="jquery-1.4.js"></script>
<script type="text/javascript">
$(document).ready(function() {
// 點擊所有 id 中包含 'buttonValidate' 的 input 標籤時執行
$("input[id^='buttonValidate']").click(function() {
var btnVal = $.trim($(this).val()); // trim 去掉前後空格
var str = $('#textareaValidate').val() + btnVal;
$('#textareaValidate').val(str);
});
});
</script>
<title>Insert title here</title>
</head>
<body>
<form id="form1" name="form1" action="" method="post">
<table id="table1" class="base_table" cellspacing="0" border="1"
style="border-collapse: collapse">
<tr>
<td>
<textarea cols="75" rows="5" id="textareaValidate"></textarea>
</td>
</tr>
<tr id="tr1">
<td>
<input id="buttonValidate1" type="button" value=" + " />
<input id="buttonValidate2" type="button" value=" - " />
<input id="buttonValidate3" type="button" value=" * " />
<input id="buttonValidate4" type="button" value=" / " />
<input id="buttonValidate5" type="button" value=" ! " />
<input id="buttonValidate6" type="button" value=" = " />
<input id="buttonValidate7" type="button" value=" < " />
<input id="buttonValidate8" type="button" value=" > " />
<input id="buttonValidate9" type="button" value=" & " />
<input id="buttonValidate10" type="button" value=" | " />
<input id="buttonValidate11" type="button" value=" ( " />
<input id="buttonValidate12" type="button" value=" ) " />
</td>
</tr>
</table>
</form>
</body>
</html>
$("input[id^='buttonValidate']") 用的是「屬性值開頭」選擇器,所有 id 以 buttonValidate 開頭的 input 都會被選中。這樣不必為 12 個按鈕逐一寫綁定,之後要新增按鈕只要延續命名規則即可,不必改 JS。
HTML 中 value=" + " 的符號兩側帶有空格,若直接取用,追加到 textarea 的內容會變成 1 + 2 這樣帶多餘空白的字串。$.trim() 把前後空白清掉,再拼接時就能完全掌控格式。
textarea 的內容必須用 .val() 取得與設定,不能用 .html() 或 .text()。這是初學時常犯的錯誤。
這份程式碼基於 jQuery 1.4,用今天的標準看有幾處可以調整:
// 用 data 屬性取代 id 前綴約定,語意更明確
<button type="button" data-op=" + ">+</button>
document.querySelectorAll('[data-op]').forEach(function(btn) {
btn.addEventListener('click', function() {
var ta = document.getElementById('textareaValidate');
ta.value += this.dataset.op.trim();
});
});
幾點說明:
$(document).ready() 在現在可以直接寫成 DOMContentLoaded 監聽,或把 script 標籤放到 body 末尾並加上 defer。$.trim() 已棄用,改用原生 String.prototype.trim()。input[id^=...] 這種依賴命名慣例的選擇器比較脆弱,改用 data-* 自訂屬性會更清楚。<button> 取代 <input type="button">,語意更貼切,也更方便放入 HTML 內容。