如何自动聚焦第一个骨干表单输入字段?

JJD*_*JJD 3 focus backbone.js backbone-views backbone-forms marionette

以下屏幕截图显示了登录和注册的组合表单:

骨干表格

以下模块用于呈现AuthView:

MyApp.module("User", function(User, App, Backbone, Marionette, $, _) {

  User.AuthView = Marionette.ItemView.extend({

    className: "reveal-modal",
    template: "user/auth",

    ui: {
      signInForm: "#signin-form",
      signUpForm: "#signup-form"
    },

    events: {
      "focus input": "onFocus"
    },

    onFocus: function() {
      console.log("Some input field has received focus.");
    },

    onRender: function() {  
      this.signInForm = new Backbone.Form({
        schema: {
          signInEmail: { 
            type: "Text", 
            title: "E-Mail address"
          },
          signInPassword: { 
            type: "Password", 
            title: "Password"
          }
        }
      }).render();
      this.ui.signInForm.prepend(this.signInForm.el);

      this.signUpForm = new Backbone.Form({
        schema: {
          signUpEmail: { 
            type: "Text", 
            title: "E-Mail address"
          },
          signUpPassword: { 
            type: "Password", 
            title: "Password"
          },
          signUpPasswordConfirmation: { 
            type: "Password", 
            title: "Password confirmation"
          }
        }
      }).render();
      this.ui.signUpForm.prepend(this.signUpForm.el);
    }

  });
});
Run Code Online (Sandbox Code Playgroud)

每当渲染时,如何自动将第一个字段聚焦在每个子表单中?第一个字段是signInEmailfor signInFormsignUpEmailfor signUpForm.
我试着听听focus input事件.当我点击其中一个输入字段时,而不是之前,会触发此类事件.


同时,受到当前答案的启发,我提出了以下辅助函数:

focusFirstFormField: function(form) {
  if (_.isUndefined(form)) {
    throw "IllegalStateException: Form is undefined."
  }
  // TODO: AuthView does not focus first sign-in field.
  var firstInput = form.find(':input:first');
  if (_.isObject(firstInput)) {
    if (firstInput.length > 0) {
      firstInput = firstInput[0];
    }
    else {
      throw "IllegalStateException: Form find returns an empty jQuery object."
    }
  }
  _.defer(function() {
    firstInput.focus();
  });
 }
Run Code Online (Sandbox Code Playgroud)

但是仍然需要改进.

Eva*_*bbs 6

事件对象是DOM事件,通常由用户触发,因此在这种情况下不是您可能想要使用的事件.

如果我正确地理解你,你想把焦点放在每个表格的第一个输入中但是因为你一次只能关注一件事而且他们在一起渲染你必须选择一个或者其他.

最简单的选择是在onRender的末尾添加另一行,专注于输入.如果您的输入正在生成如下输入:

<input type="text" name="signInEmail">
Run Code Online (Sandbox Code Playgroud)

然后你可以添加:

this.$('[name=signInEmail]').focus();
Run Code Online (Sandbox Code Playgroud)

如果不是,你将不得不更改选择器.$(xxxx).focus()以适应.