3

次のスクリーンショットは、サインインとサインアップを組み合わせたフォームを示しています。

バックボーンフォーム

をレンダリングするために、次のモジュールが使用されます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);
    }

  });
});

サブフォームがレンダリングされるたびに、各サブフォームの最初のフィールドに自動的にフォーカスするにはどうすればよいですか? 最初のフィールドsignInEmailsignInFormおよびsignUpEmailですsignUpForm。イベント
を聞いてみました。focus inputこのようなイベントは、入力フィールドの 1 つをクリックする前ではなく、クリックしたときにトリガーされます。


一方、現在の回答に触発されて、次のヘルパー関数を思いつきました。

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

とはいえ、まだまだ改善が必要です。

4

4 に答える 4

1

私がonRender行う方法について:

$(this.el).find(':input[autofocus]').focus();

そして、autofocus=""フラグを HTML ノードに追加します。これはリフレッシュに機能します。

于 2016-10-31T13:23:58.500 に答える