今天遇到了这个问题,在网上搜了搜,感觉这篇文章不错,就转载过来了,谢谢原文作者!

在使用jquery中的确trim属性时,:$(‘input[type=\'text\']:eq(0)‘).val().trim() ,在ie7/8报错:对象不支持“trim”属性或方法,下面我来给大家介绍一下解决办法。

解决方法:

方法1:

使用jquery里面的全局函数$.trim()代替原生js方法trim():$.trim($("input[type='text']:eq(0)").val().trim());

方法2:

使用原生js来扩展String方法

1.写成类的方法:[   调用格式: str.trim();   ]

 代码如下 复制代码

<script type="text/javascript">

Function.prototype.method = function(name, func) {

  this.prototype[name] = func;

  return this;

};

if(String.prototype.trim){ //判断下浏览器是否自带有trim()方法

String.method('trim', function() {

return this.replace(/^s+|s+$/g, '');

});

String.method('ltrim', function() {

return this.replace(/^s+/g, '');

});

String.method('rtrim', function() {

return this.replace(/s+$/g, '');

});

</script>


例子

 代码如下 复制代码

<input id="demo" type="" value="      左右有空格        " /> <a href="javascript:;" <script type="text/javascript">
 Function.prototype.method = function(name, func) {
   this.prototype[name] = func;
   return this;
 };
 if(!String.prototype.trim){ //判断下浏览器是否自带有trim()方法
 String.method('trim', function() {
 return this.replace(/^s+|s+$/g, '');
 });
 String.method('ltrim', function() {
 return this.replace(/^s+/g, '');
 });
 String.method('rtrim', function() {
 return this.replace(/s+$/g, '');
 });
 }
 //测试调用方法: trim()
 document.getElementById("demo").select();
 var str=document.getElementById("demo").value;
 function test(){
 document.getElementById("demo").value=str.trim(); //可换成str.ltrim() 或 str.rtrim()
 document.getElementById("demo").select();
 }
</script>

解决方法二

写成函数:[     调用格式: trim(str)   ]

 代码如下 复制代码

<script type="text/javascript">

 function trim(str){ //删除左右两端的空格  

     return str.replace(/(^s*)|(s*$)/g, "");

   }

   function ltrim(str){ //删除左边的空格

       return str.replace(/(^s*)/g,"");

   }

   function rtrim(str){ //删除右边的空格

       return str.replace(/(s*$)/g,"");

   }

</script>

实例

 代码如下 复制代码

 

 <input id="demo" type="" value="      左右有空格        " /> <a href="javascript:;" <script type="text/javascript">
  function trim(str){ //删除左右两端的空格  
      return str.replace(/(^s*)|(s*$)/g, "");
   }
   function ltrim(str){ //删除左边的空格
       return str.replace(/(^s*)/g,"");
   }
   function rtrim(str){ //删除右边的空格
       return str.replace(/(s*$)/g,"");
   }
 //测试调用方法: trim()
 document.getElementById("demo").select();
 var str=document.getElementById("demo").value;
 function test(){
 document.getElementById("demo").value=trim(str); //可换成str.ltrim() 或 str.rtrim()
 document.getElementById("demo").select();
 }
</script>