使用 jquery 验证插件滚动到特定错误

Scroll to particular error with jquery validate plugin

我在这里找到了关于如何处理错误和滚动的很好参考 (How to fire an event on error in jquery validator plugin),但我不明白如何滚动到特定错误。假设我有 20 个元素可能会在移动设备上和您的移动设备上发生错误,现在如果有错误我可以滚动到顶部,但那可能不是错误所在!

我禁用了 focusInvalid,因为它会以一种突兀的方式在移动设备上调出键盘,并且无论如何都不会滚动到该元素。

有没有办法用插件或任何自定义代码来做到这一点?

这是我现在无效的处理程序。

invalidHandler: function(form, validator){
                $('html, body').animate({scrollTop: '0px'}, 300);
            },

滚动到错误不是这个插件的一部分。您必须将内置回调函数之一与您自己的动画代码一起使用...

  • invalidHandler 不允许您访问各个错误消息。当您单击无效表单上的提交按钮时,它就会触发。因此,您不能使用此选项滚动到单个字段。

  • showErrors 将使您能够访问各个错误消息和元素。但是,您必须弄清楚要滚动到哪一个,因为所有未决错误都会立即列在此处。下面的代码将滚动到出现错误的第一个元素(表单上最高的元素)。

    showErrors: function (errorMap, errorList) {
          // errorList[0].element; // <- index "0" is the first element with an error
    
          if (typeof errorList[0] != "undefined") {
              var position = $(errorList[0].element).position().top;
              $('html, body').animate({
                  scrollTop: position
              }, 300);
          }
          this.defaultShowErrors(); // keep error messages next to each input element   
    }
    

演示:http://jsfiddle.net/tvr6f9j1/1/