我試圖讓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.
什麼'this'? – SLaks
@SLaks我試圖引用$(「emailSubject」)。使用$(this)不是正確的方法嗎? – dmr
將'size'屬性設置爲字符數不會達到您想要的。見自己:http://jsfiddle.net/FafBQ/ – thirtydot