代码之家  ›  专栏  ›  技术社区  ›  Björn C

使用jQuery选择输入值的第一个字符

  •  3
  • Björn C  · 技术社区  · 9 年前

    我有一些通过jQuery预先填充的输入字段。我想获取输入的值,检查它是否以“x”开头,如果是,则选择该x(这样用户可以通过键入其他内容快速更改x)。

    我知道这里有这样一个问题: Selecting Part of String inside an Input Box with jQuery

    但这是一个非常老的问题,它并没有真正使用jQuery!

    那么,如何选择输入值中的x?

    <input class="input" type="text" value="x*500*500" />
    

    我试过:

    var input = $('.input');
    input.setSelectionRange(0, 2); // Highlights "X"
    input.focus();
    

    错误: Uncaught TypeError: input.setSelectionRange is not a function setSelectionRange 不赞成?

    3 回复  |  直到 9 年前
        1
  •  3
  •   Community Mohan Dere    6 年前

    [0] . setSelectionRange 是纯JavaScript,处理纯JS对象。它不知道jQuery对象是什么。顺便说一下,我将第二个参数从2改为1。 MDN has described ?

    片段

    var input = $('.input')[0];
    input.setSelectionRange(0, 1); // Highlights "X"
    input.focus();
    <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
    <input class="input" type="text" value="x*500*500" />
        2
  •  1
  •   RAUSHAN KUMAR    9 年前

    var input = $('.input').val();
    if(input.str.startsWith('X')){
        e.focus();
        var pos = e.val().indexOf('x');
        e.prop({
            'selectionStart': pos,
            'selectionEnd': pos + 1
        });
    }
    
        3
  •  1
  •   Keith    9 年前

    var e = $('[data-field=test]');
    setTimeout(function () {
      e.focus();
      var pos = e.val().indexOf('x');
      e.prop({
        'selectionStart': pos,
        'selectionEnd': pos + 1
      });
    }, 100);
    <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
    <input data-field="test" value="hello x 123">