jquery $.trim()去除字符串空格詳解javascript
jQuery.trim()
函數用於去除字符串兩端的空白字符。css
該函數能夠去除字符串開始和末尾兩端的空白字符(直到遇到第一個非空白字符串爲止)。它會清除包括換行符、空格、製表符等常見的空白字符。html
若是參數str
不是字符串類型,該函數將自動將其轉爲字符串(通常調用其toString()方法)。若是參數str
爲null或undefined,則返回空字符串("")。java
jQuery.trim()
函數的返回值爲String類型,返回去除兩端空白字符串後的字符串。jquery
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN"> <html> <head> <base href="<%=basePath%>"> <title>My JSP 'index.jsp' starting page</title> <meta http-equiv="pragma" content="no-cache"> <meta http-equiv="cache-control" content="no-cache"> <meta http-equiv="expires" content="0"> <meta http-equiv="keywords" content="keyword1,keyword2,keyword3"> <meta http-equiv="description" content="This is my page"> <!-- <link rel="stylesheet" type="text/css" href="styles.css"> --> </head> <body> <input type="text" name="" id="results" value=""/><br> <button id="showBtn">showBtn</button> <button id="showBtn1">showBtn1</button> <script src="http://code.jquery.com/jquery-1.5.js"></script> <script type="text/javascript"> $("#showBtn").click( function(){ var content = $('#content').val(); if($.trim(content) == ''){ alert('空'); } } ); $("#showBtn1").click( function(){ var content = $('#content').val(); if(content.trim() == ''){ alert('空'); } } ); </script> </body> </html>
不能理所固然的想跟java同樣。用一個字符串點方法。jsp
錯誤寫法:函數
$("#showBtn1").click( function(){ var content = $('#content').val(); if(content.trim() == ''){ alert('空'); } } );
說明: 上面的寫法在firefox下不會報錯,在ie和谷歌下確會報錯。ui
正確寫法:spa
$("#showBtn").click( function(){ var content = $('#content').val(); if($.trim(content) == ''){ alert('空'); } } );
參考過的資料firefox
參考:http://www.365mini.com/page/jquery_trim.htm