【问题标题】:jquery each for all text boxesjquery each 用于所有文本框
【发布时间】:2011-08-25 11:03:48
【问题描述】:

我正在使用以下脚本在每个文本框上绑定一个按键事件,以便在达到最大长度时,焦点将切换到下一个输入字段。将类名作为参数传递给函数。

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');
});

正如我提到的两个不同的输入......它运行良好。但是有什么办法可以让它获取类名并遍历每个输入框以附加按键事件。

【问题讨论】:

    标签: javascript jquery


    【解决方案1】:

    如果我理解正确,您想将相同的事件处理程序附加到 every input 字段吗?只需使用选择器:

    $(':text') 
    

    (对于所有 input type="text")字段。

    所以改变

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

    到:

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

    【讨论】:

    • 如果你使用$('input[type="text"]'),jQuery 可以使用原生浏览器方法。
    • 它会给你同样的结果,但是:text不是一个CSS选择器,它是一个jQuery伪选择器。如果您使用有效的 CSS 选择器,jQuery 将直接使用本机浏览器方法。出于性能原因,首选有效的 CSS 选择器。
    • 你是对的。 jQuery 站点上的语法是 $('[type=text]')。 api.jquery.com/text-selector
    【解决方案2】:

    如果我理解正确,您只需要使用类型选择器进行输入。您还可以摆脱调用 each 来遍历输入,因为绑定事件以乘以元素通过它们交互。因此,您可以将代码更改为以下内容:

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

    【讨论】:

      【解决方案3】:

      这很好用。

      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);
      });
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2021-02-28
        • 2011-09-06
        • 2015-06-05
        • 2015-05-13
        • 2013-06-03
        • 1970-01-01
        • 1970-01-01
        • 2018-07-02
        相关资源
        最近更新 更多