DIV CSS 佈局教程網

用 jQuery.type() 判斷資料型別
編輯:關於JavaScript     

在寫運算或轉型之前,必須先確認手上這份資料到底是字串、數字還是其他型別,否則很容易出現「1 + 1 = 11」這類拼接錯誤。jQuery 提供了 jQuery.type() 來做這件事。

先準備一個簡單的樣式:

 <style type="text/css"> div { width:200px; height:100px; background-color:#660; } </style> 

接著用 css() 取出寬度並檢查它的型別:

 <script type="text/javascript" src="mytest/jQuery/jquery-1.8.3.js"></script> <script type="text/javascript"> $(document).ready(function(){ var width=$("div").css("width"); alert(jQuery.type(width)); }) </script> 
 <div></div>

執行後會發現回傳的是 string,而不是 number。這正是很多位移計算出錯的根源——$("div").css("width") 得到的是像 "200px" 這樣的字串,直接拿來加減會出问题,必須先 parseInt() 或 parseFloat() 轉成數字。

相較於只能判斷「是不是陣列」的 typeof,jQuery.type() 能更精確地區分 string、number、function、object、array、null、undefined 等型別,除錯時特別好用。

XML學習教程| jQuery入門知識| AJAX入門| Dreamweaver教程| Fireworks入門知識| SEO技巧| SEO優化集錦|
Copyright © DIV+CSS佈局教程網 All Rights Reserved