【问题标题】:Tabbing to next input using querySelector使用 querySelector 跳转到下一个输入
【发布时间】:2021-11-16 23:56:50
【问题描述】:

一旦满足 maxlength,我试图将输入字段选项卡切换到下一个字段,但我不断收到错误 Failed to execute 'querySelector' on 'Document': 'name=2' is not a valid selector.。我已经阅读了mozialla's explanation of a querySelector 并尝试使用元素id 来聚焦(),但这会产生相同的错误。我想我不明白如何正确制作选择器以传递给 querySelector。

我的输入字段只显示 2 我有 3:


    <Input
              onChange={dateChange("month")}
              value={date.month}
              id="1"
              maxLength={2}
              type="number"
            />
            <span className="sep">/</span>
            <Input
              onChange={dateChange("day")}
              value={date.day}
              name="2"
              id="2"
              maxLength={2}
              type="number"
            />

我的 onChange:


    const dateChange = (field) => (e) => {
    
            const fieldIndex = e.target.name;
            let fieldIntIndex = parseInt(fieldIndex, 10);
            // format to fit
            let value = e.target.value;
          
            if (value.length === e.target.maxLength) {
              if (fieldIntIndex < 3) {
                const nextfield = document.querySelector(
                  `name=${fieldIntIndex + 1}`
                );
                console.log(nextfield);
                if (nextfield !== null) {
                  nextfield.focus();
                }
              }
            }
        
            const d = { ...date, [field]: value };
            setDate(d);
            debounceCallback(handleDateInputChange, d);
          };

我还在学习,所以任何关于这方面的建议都会很棒 :) 在此先感谢!

【问题讨论】:

    标签: javascript reactjs jquery-selectors focus


    【解决方案1】:

    首先,我认为这样设置事件监听器是不正确的:

    onChange={dateChange("month")}
    

    如果您这样做,您实际上是在页面呈现期间执行该功能。该函数应在事件发生时执行。正确的做法是:

    onChange={dateChange}
    

    如果您还想为函数添加参数,那么您应该这样做:

    onChange={dateChange.bind(this, "month")}
    

    此外,关于查询选择器,我认为正确的语法是:

    const nextfield = document.querySelector(`input[name='${fieldIntIndex + 1}']`);
    

    您的 name 属性设置为输入元素,因此我们使用 input[name]。
    name 也有一个字符串值,所以我们使用 input[name='']。
    最后我们想参数化地设置名称值,所以我们使用 `input[name='${parameter}']`。

    你可以找到绑定JavaScript函数here的MDN文档和querySelectorhere的文档。

    编辑:在输入之间导航的另一种选择是 tabindex 属性。您可以在here找到更多相关信息。

    【讨论】:

      【解决方案2】:

      名称是一个字符串所以我认为你应该这样做(添加括号) name='${fieldIntIndex + 1}'

      【讨论】:

      • 如果我没有将name= 包装在一个字符串中,这不起作用它会导致错误...您是说您认为问题在于整个项目是一个字符串吗?比如“name=2”?
      猜你喜欢
      • 2012-06-20
      • 2017-09-29
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2011-12-04
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多