我很难完全理解这段代码的工作原理。这只是从 Bootstrap 复制和粘贴的表单验证代码。
我的问题从这一行开始 var validation = Array.prototype.filter.call(表单, 函数(表单)
在我看来,它正在创建一个名为 validation 的数组,其中包含类名为“needs-validation”的任何元素。然后是调用匿名函数并传入整个表单并运行后续代码行
form.addEventListener('submit', function(event) {
if (form.checkValidity() === false) {
event.preventDefault();
event.stopPropagation();
}
在每个包含类名“needs-validation”的元素上?
<script>
// Example starter JavaScript for disabling form submissions if there are invalid fields
(function() {
'use strict';
window.addEventListener('load', function() {
// Fetch all the forms we want to apply custom Bootstrap validation styles to
var forms = document.getElementsByClassName('needs-validation');
// Loop over them and prevent submission
var validation = Array.prototype.filter.call(forms, function(form) {
form.addEventListener('submit', function(event) {
if (form.checkValidity() === false) {
event.preventDefault();
event.stopPropagation();
}
form.classList.add('was-validated');
}, false);
});
}, false);
})();
此代码成功验证了表单上的输入。我只是不明白它是如何工作的。
最佳答案
方法document.getElementsByClassName
返回一个HTMLCollection
,乍一看它类似于Array但是HTMLCollection
没有方法 .filter
, .map
, reduce
等
因此,为了使用这些方法,我们需要将 HTMLCollection
转换为数组。
或者我们可以使用特定于 javascript 的:Array.prototype.filter
在一个对象上进行迭代,如果你在 HTMLCollection
上查看详细信息,什么 document.getElementsByClassName
返回它有键并且它是 iterable
。所以我们可以调用方法 Array.prototype.filter.call(
并将我们的 HTMLCollection
作为上下文(第一个参数)传递,第二个参数将是一个将调用的函数集合中的每个元素。
关于 call() 方法的更多信息 https://gomakethings.com/what-the-hell-is-the-call-method-and-when-should-you-use-it/
关于javascript - Array.prototype.filter.call(forms, function(form) 这是在做什么?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57419277/