As Alien Webguy said https://stackoverflow.com/questions/6819548/onload-fit-input-size-to-length-of-text/6819648#6819648, you're trying to call a jQuery function (val
) on what's probably a raw DOM element or the window
object (you haven't shown enough context for us to know what this
is, but the error tells us it's not a jQuery instance) the document
object (because that's what jQuery sets this
to when calling your ready
handler). (Your update clarified it.) So the first thing is to get the correct reference for the field and wrap it in a jQuery instance.
但单独来说,如果你设置size
对于字符数,该字段几乎肯定会比您想要的大得多。那是因为size
以统一的字符宽度工作。
相反,通常的做法是使用与输入元素具有相同字体系列、样式、大小、文本装饰等的页外元素来测量实际字符串。像这样的东西(实时复制 http://jsbin.com/ifuzop):
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");
}
});
请注意,我也在调整各种事件的大小;我怀疑那里的列表是否全面,但它给了你一个想法。