簡體   English   中英

jQuery的所有所有文本框

[英]jquery each for all text boxes

我正在使用以下腳本在每個文本框上綁定一個按鍵事件,以便在達到最大長度時,焦點將切換到下一個輸入字段。 將類名作為參數傳遞給函數。

function autoFocusPhoneFields(txtbox1ID,txtbox2ID) {
    $('input.'+txtbox1ID+', input.'+txtbox2ID+'').each(function() {
        $(this).bind('keypress', function(){
        if(this.value.length == $(this).attr('maxlength')) {
            $(this).next('input').focus();
        } 
     });
});
}
    $(document).ready(function(){
    autoFocusPhoneFields('mobileprefix','mobilecode');
});

正如我已經提到的兩個不同的輸入..它運行良好。 Butis周圍有任何方法,這樣它將獲取類名並在每個輸入框中運行以附加按鍵事件。

如果我理解正確,您想將相同的事件處理程序附加到每個 input字段嗎? 只需使用選擇器:

$(':text') 

(對於所有input type="text" )字段。

所以只要改變

$('input.'+txtbox1ID+', input.'+txtbox2ID+'').each(function() {

至:

$(':text').each(function() {

如果我正確地理解了您,則只需使用類型選擇器進行輸入。 您還可以擺脫調用每個輸入來迭代輸入的麻煩,因為綁定乘法事件會通過它們進行交互。 因此,您可以將代碼更改為以下內容:

var autoFocusPhoneFields = function () {
    $('input:text').keypress(function() {
        if(this.value.length == $(this).attr('maxlength'))
            $(this).next('input').focus();            
    });
}
$(autoFocusPhoneFields);

這很好。

的HTML

<input id="one" class="inp" maxlength="5" />
<input id="two" class="inp" maxlength="3" />
<input id="three" class="inp" maxlength="2" />

JS部分

$(function(){
    var onpress = function(){
        var val = $(this).val();
        var next_input = $(this).next('input');
        var mx = $(this).attr('maxlength');
        try {
            mx = Number(mx);
            if (next_input.length >= 1 && val.length >= mx){
                next_input.focus();
            }
        } catch(x){}

    }

    $('input.inp').bind('keypress', onpress);
});

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM