JS 中透過表單等方式取得的資料,預設都是 string 字串型別。若要進行數值運算,必須先用 parseInt 轉換成數字,否則容易出現字串拼接的錯誤結果。
HTML 程式碼:
<div id="archive">
<input type="hidden" name="page" value="1" />
</div>
JS 程式碼:
$("#archive").bind('click',function(){
var page=$("input[name='page']").val();
//要用parseInt進行數值的運算
$("input[name='page']").val(parseInt(page)+1);
});
這裡的 page 透過 val() 取出後是字串「1」,若直接 +1 會變成字串拼接的「11」。使用 parseInt(page) 先轉為數字,再加 1,才能得到正確的「2」。這是在做分頁、累加計數等運算時經常忽略卻很關鍵的細節。