在类上使用js而不是输入id加载页面时自动关注字段

时间:2018-09-07 18:42:07

标签: javascript angularjs

我有一个网站,我希望在页面加载时使用js将焦点设置为输入字段。我无法更改以下代码。这是输入标签:

final MutableLiveData<List<Integer>> vals = new MutableLiveData<>();
List<Integer> intVals = new ArrayList<>();
intVals.add(0);
vals.setValue(intVals);

tv.setText("" + vals.getValue().get(0));

vals.observe(this, new Observer<List<Integer>>() {
    @Override
    public void onChanged(@Nullable List<Integer> integers) {
        int firstVal = integers.get(0);
        Log.d(TAG, "onChanged val " + firstVal);
        tv.setText("" + firstVal);
    }
});

btn.setOnClickListener(new View.OnClickListener() {
    @Override
    public void onClick(View v) {
        // first val in List is incremented but onChanged isn't called, why?
        int newVal = vals.getValue().get(0) + 1;
        vals.getValue().set(0, newVal);
        Log.d(TAG, "set val at index 0 to " + newVal);
    }
});

我在下面尝试了js来查看其他类似主题,但是没有运气:

input class="form-control ng-pristine ng-valid ng-scope ng-touched"
      ng-model="query.q" type="text"
      placeholder="Enter search terms - use quotes for phrases"
      kw-clearable-input=""

任何帮助将不胜感激。谢谢。

2 个答案:

答案 0 :(得分:2)

问题在于焦点函数中未定义元素。

正确定义后,它就会起作用。

function setFocusToTextBox()
{ 
  let element = document
    .getElementsByClassName("form-control ng-pristine ng-valid ng-scope ng-touched")[0]; 
  
  element.focus();
}

setFocusToTextBox();
<input class="form-control ng-pristine ng-valid ng-scope ng-touched" ng-model="query.q" type="text" placeholder="Enter search terms - use quotes for phrases" kw-clearable-input=""/>

您还可以删除元素并以这样的焦点加入查询:

function setFocusToTextBox()
{ 
  document.getElementsByClassName("form-control ng-pristine ng-valid ng-scope ng-touched")[0].focus();
}

setFocusToTextBox();
<input class="form-control ng-pristine ng-valid ng-scope ng-touched" ng-model="query.q" type="text" placeholder="Enter search terms - use quotes for phrases" kw-clearable-input=""/>

此处提供了所提供的布局:

function setFocusToTextBox()
{ 
  document.querySelector( '.input-group.dropdown input' ).focus();
}

setFocusToTextBox();
<div class="input-group dropdown" dropdown="" keyboard-nav="" is-open="opt.showFqDropdown"> <span style="position: relative;"> <input class="form-control ng-pristine ng-valid ng-scope ng-touched" ng-model="query.q" type="text" placeholder="Enter search terms - use quotes for phrases" kw-clearable-input=""/>
</span>
</div>

答案 1 :(得分:1)

您可以使用autofocus

<input class="form-control ng-pristine ng-valid ng-scope ng-touched" ng- 
 model="query.q"
 type="text"
 placeholder="Enter search terms - use quotes for phrases"
 kw-clearable-input="" 
 autofocus>