2011-07-25 9 views
4

我試圖讓jQuery測試輸入框onLoad中文本的長度並更改輸入框的大小以適合。這裏是我的代碼嘗試至今:Onload擬合輸入大小到文本長度

$("#emailSubject").attr('size', this.val().length); 

,我發現了以下錯誤:

this.val is not a function

我在做什麼錯?

更新:現在我不再得到第一個錯誤,但長度顯示爲0,即使它不應該是。 (我正在使用警報來檢查長度是多少)。爲什麼會這樣呢?

更新:以下是代碼背景:

$(
     function() 
     { 
      //works correctly 
      alert($("#emailSubject").val().length); 
      //throws error 
      $("#emailSubject").attr('size', ($(this).val().length)); 
     } 
    ) 

新無錯誤長度正確顯示警報,但我得到的錯誤:

Index or size is negative or greater than the allowed amount.

+0

什麼'this'? – SLaks

+0

@SLaks我試圖引用$(「emailSubject」)。使用$(this)不是正確的方法嗎? – dmr

+1

將'size'屬性設置爲字符數不會達到您想要的。見自己:http://jsfiddle.net/FafBQ/ – thirtydot

回答

8

由於Alien Webguy said,你想呼籲一個jQuery函數(val)什麼是可能是你還沒有表現出足夠的上下文讓我們知道什麼this是原始DOM元素或window對象(,但錯誤告訴我們這不是一個jQuery實例)document對象(因爲這是什麼時jQuery設置this當調用你的ready處理程序)。 (你的更新澄清了它。)因此,第一件事是獲得該字段的正確引用並將其包裝在一個jQuery實例中。

但是,如果將size設置爲字符數,則該字段幾乎肯定會比您想要的大得多。這是因爲size以統一的字符寬度工作。

相反,通常情況下,使用具有相同字體系列,樣式,大小,文本修飾等作爲輸入元素的離頁元素來測量實際字符串。像這樣的東西(live copy):

CSS:

#theField, #measure { 
    font-family: serif; 
    font-size: 12pt; 
    font-style: normal; 
} 
#measure { 
    position: absolute; 
    left: -10000px; 
    top: 0px; 
} 

HTML:

<input type='text' id='theField' value=''> 
<span id="measure"></span> 

的JavaScript:

jQuery(function($) { 
    var field; 

    // Hook up some events for resizing 
    field = $("#theField"); 
    field.bind("change keypress click keydown", function() { 
    resizeIt(field); 
    }); 

    // Resize on load 
    resizeIt(field); 

    // Function to do the work 
    function resizeIt(field) { 
    var measure = $("#measure"); 
    measure.text(field.val()); 
    field.css("width", (measure.width() + 16) + "px"); 
    } 
}); 

注意,這裏我調整各種事件以及;我懷疑這個列表是否全面,但它給了你一個想法。

+2

+1得到它之內。 「尺寸」完全正確。 – thirtydot

0

你需要將this圍成jQuery對象$(this)

+0

或者,同樣,使用'this.value.length'來代替。 –

+0

啊,我只是保持'jQuery' – Phil

+1

有用牢記:http://stackoverflow.com/questions/4651923/when-to-use-vanilla-javascript-vs-jquery/ – thirtydot

2

在這裏以令人困惑的方式使用$(this),因爲我們無法看到代碼的其餘部分如何發揮作用。

例如:

$('body').bind('keypress',function(){ 
    $('#emailSubject').attr('size', $(this).val().length); 
}); 

在上面的代碼,$(this)$('body'),你需要做這樣的事情:

$('body').bind('keypress',function(){ 
    var _this = $('#emailSubject'); 
    _this.attr('size', _this.val().length); 
}); 

但是,如果你的事件處理程序綁定到$('#emailSubject')然後$(this)會工作,你甚至可以使用它兩次:

$("#emailSubject").bind('keypress',function(){ 
    $(this).attr('size', $(this).val().length); 
}); 
相關問題