我如何重构以避免重复?

How Can I Refactor To Avoid Duplication?

$('#foo').validate({
  errorPlacement: (e, el) => {
    /**
     * /* Insert .error after offending <input>'s <label>.
     */
    e.insertAfter(el.next('.form__label')).animate({
      opacity: 1,
      top: '-=10px',
    }, 'fast');
  },
  messages: {
    tc: 'Please accept our Terms & Conditions!',
  },
});

$('#bar').validate({
  errorPlacement: (e, el) => {
    /**
     * /* Insert .error after offending <input>'s <label>.
     */
    e.insertAfter(el.next('.form__label')).animate({
      opacity: 1,
      top: '-=10px',
    }, 'fast');
  },
});

我正在使用 jqueryvalidation.org 在我的页面上使用两个不同的 <form> 容器。这工作正常,但是,我确信有更好的方法来推断 errorPlacement 对象,对吧?我只是现在没看到它...

我试过这样的事情:

/**
 * Customize placement of created error labels.
 * (https://jqueryvalidation.org/validate/)
 * @param {$} e created error label
 * @param {$} el invalid element
 */
function ep(e, el) {
 // Insert .error after offending <input>'s <label>.
   e.insertAfter(el.next('.form__label')).animate({
      opacity: 1,
      top: '-=10px',
    }, 'fast');
}

$('#foo').validate({
  errorPlacement: function ep(e, el) {
  // Insert .error after offending <input>'s <label>.
  e.insertAfter(el.next('.form__label')).animate({
      opacity: 1,
      top: '-=10px',
    }, 'fast');
   },
  messages: {
    tc: 'Please accept our Terms & Conditions!',
  },
});

$('#bar').validate({
  errorPlacement: ep(e, el), // This throws error of 'unknown' e
});

您正在将 将被调用的函数 设置为 已被调用的函数

当您执行 errorPlacement: ep(e, el) 时,ep(e, el) 的函数部分在您设置对象时调用,而不是在触发 errorPlacement 时调用。您只需要传递函数名称本身而不需要括号。

$('#bar').validate({
  errorPlacement: ep,
});

不过,如何最好地重构这个问题可能过于基于意见而无法真正回答。但是你将函数拆分出来的做法似乎是正确的。

没有必要,因为有一个叫.setDefaults()的东西已经是这个插件的一部分了。您放入其中的任何内容都将成为页面上所有 .validate() 实例的默认值。

$.validator.setDefaults({ // <- will be used on all instances of .validate() on this page
    errorPlacement: function(e, el) {
        e.insertAfter(el.next('.form__label')).animate({
            opacity: 1,
            top: '-=10px',
        }, 'fast');
    }
});

$('#foo').validate({
    messages: {
        tc: 'Please accept our Terms & Conditions!',
    }
});

$('#bar').validate({
    // other options
});