2010-08-09 40 views
104

我利用修剪的()像這樣:IE8和JQuery的裝飾()

if($('#group_field').val().trim()!=''){ 

哪裏group_field是文本類型的輸入元素。這在Firefox但是當我嘗試在IE8它給了我這個錯誤:

Message: Object doesn't support this property or method 

當我刪除修剪(),它工作正常的IE8。我認爲我使用trim()的方式是正確的?

感謝所有的幫助

回答

201

試試這個:

if($.trim($('#group_field').val()) != ''){ 

更多信息:

+1

謝謝,我認爲JQuery的功能是連鎖能力,這就是他們如何工作! – Abs 2010-08-09 11:01:24

+0

@Abs:不客氣... – Sarfraz 2010-08-09 11:01:43

+38

@Abs:'val()'不會返回一個jQuery對象,所以鏈接不在選項中。你正在調用一個字符串的'trim()'方法,但IE不知道'String.trim'。 – janmoesen 2010-08-09 11:08:38

15

你應該用$.trim,李ke這:

if($.trim($('#group_field').val()) !='') { 
    // ... 
} 
11

據我所知,Javascript字符串沒有方法修剪。 如果你想使用的功能飾件,然後用

<script> 
    $.trim(string); 
</script> 
+1

請[不要鏈接到w3schools](http://www.w3fools.com/)! – 2013-08-07 23:13:37

3

要使用全局類型的文本微調輸入的jQuery:

/** 
* Trim the site input[type=text] fields globally by removing any whitespace from the 
* beginning and end of a string on input .blur() 
*/ 
$('input[type=text]').blur(function(){ 
    $(this).val($.trim($(this).val())); 
}); 
10

另一種選擇將是直接的情況下,定義上String方法它缺少:

if(typeof String.prototype.trim !== 'function') { 
    String.prototype.trim = function() { 
    //Your implementation here. Might be worth looking at perf comparison at 
    //http://blog.stevenlevithan.com/archives/faster-trim-javascript 
    // 
    //The most common one is perhaps this: 
    return this.replace(/^\s+|\s+$/g, ''); 
    } 
} 

然後trim不論何種瀏覽器的工作:

var result = " trim me ".trim();