我有一個基本輸入文本,用戶可以在其中輸入一些數字。只要用戶輸入數字,輸入寬度就會被調整(更大或更小)。調整內容更改時輸入類型文本的大小
我的問題:當數字不是直接鍵入,而是通過代碼注入時,輸入寬度不會被調整。
有什麼想法?
這裏是一個jsFiddle重現該問題
1:嘗試在輸入文本鍵入的東西:你會看到這個輸入寬度更大。
第二種:嘗試點擊確定按鈕(注入一些數字):您將看不到輸入寬度的變化。
以下是基本代碼:
<input type="text" id="myField" size="5">
<input type="button"Value="Ok" data-bind="click: buttonClicked">
var ViewModel = function(first, last) {
this.buttonClicked = function() {
$('#myField').val('123456789123456789123456789');
alert('Some numbers are directly injected but the input text is not adjusted');
}
};
ko.applyBindings(new ViewModel());
function resizeInput() {
$(this).attr('size', $(this).val().length);
}
$('input[type="text"]')
// event handler
.keyup(resizeInput)
// resize on page load
.each(resizeInput);
感謝。
捕獲注入數字的長度並添加到$(this).val()。length並將其應用於屬性。 – Anup