用于 HTML5 的 JavaScript 必填字段设置为在 Safari 中工作

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/19613923/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-27 16:10:28  来源:igfitidea点击:

JavaScript for HTML5 required field set up to work in Safari

javascriptphpjqueryhtml

提问by John Siniger

I am using the following script to change the HTML5 requiredattribute of my inputelements. I am wonder whether there is a way to modify this script to make it also work in Safari browsers, since Safari does not support this attribute.

我正在使用以下脚本来更改元素的 HTML5required属性input。我想知道是否有办法修改此脚本以使其也能在 Safari 浏览器中运行,因为 Safari 不支持此属性。

Here is the script:

这是脚本:

$(document).ready(function() {
    $_POST = array();
    var elements = document.getElementsByTagName("INPUT");
    for (var i = 0; i < elements.length; i++) {
        elements[i].oninvalid = function(e) {
            e.target.setCustomValidity("");
            if (!e.target.validity.valid) {
                e.target.setCustomValidity("This field can't be blank");

            }
        };
        elements[i].oninput = function(e) {
            e.target.setCustomValidity("");

        };
    }
})

采纳答案by Machavity

Check out this page here. It contains a hacky solution that should add the desired functionality

在此处查看此页面。它包含一个应该添加所需功能的hacky解决方案

http://www.html5rocks.com/en/tutorials/forms/constraintvalidation/#toc-safari

http://www.html5rocks.com/en/tutorials/forms/constraintvalidation/#toc-safari

回答by arleslie

You can also do this:

你也可以这样做:

var valid = true;
$('input[required]').each(function() {
    if (this.value == '') {
        // Alert or message to let them know
        valid = false;
        return false; // stop on first error, or remove this and it'll go through all of them.
    }
});

if (valid === false) {
    return false;
}

回答by Evan

You're going to need to run the check yourself using an event handler on your form submission. In that handler, you run the check yourself, and if it fails, you display whatever error message and block the submission using preventDefaultor return false.

您将需要在表单提交时使用事件处理程序自己运行检查。在该处理程序中,您自己运行检查,如果检查失败,则显示任何错误消息并使用preventDefault或阻止提交return false

An example can be found here, though as it notes, you need to be careful if you use checkValidity as your means of checking the form.

可以在此处找到一个示例,但正如它所指出的,如果您使用 checkValidity 作为检查表单的方式,则需要小心。