繁体   English   中英

如何使用JavaScript检测文档中是否存在HTML5有效的doctype?

[英]How to detect if an HTML5 valid doctype is present in the document using JavaScript?

我想知道是否只是一种方法来检测是否存在doctype - 最好只是HTML5 doctype。 我不想在字符串或任何内容中返回它(虽然我已经尝试过这个问题,在这里提出类似问题,请参阅下面的代码),而我只是想看看它是否不存在。 例如,如果不存在,则调用alert ,然后return false ,或者如果存在,则调用接受函数。

就像我之前说的那样,我已经在这里阅读了其他帖子和其他论坛上的其他帖子但是它们似乎都没有与我的答案相符,或者我可能错误地解释了代码,如果有的话请告诉我。

我已经尝试过的代码如下:

    var msg = {
        noHTML5: "You're pages document type is either not defined or not compliant with HTML5."
    },

    node = document.doctype,
    thisNodeHTML = "<!DOCTYPE " + node.name + (node.publicId ? ' PUBLIC"' + node.publicId + '"' : '') + (!node.publicId && node.systemId ? ' SYSTEM' : '') + (node.systemId ? ' "' + node.systemId + '"' : '') + ">";

    if(!thisNodeHTML) {
        alert(msg.noHTML5);

        return false;
    }

    else {
       // success = true;
    }

编辑:

但是,我注意到,一旦我在html文件中删除了doctype,Chrome的错误控制台会捕获它并显示错误。 也许我的条件语句的语法不正确?

如果没有doctype, document.doctypenull ,因此您的错误。 调整你的方法在这种情况下返回false,你应该是好的。 样品检测功能,基于doctype:

var is_html5 = function () {
    if (document.doctype === null) return false;

    var node = document.doctype;
    var doctype_string = "<!DOCTYPE " + node.name + (node.publicId ? ' PUBLIC"' + node.publicId + '"' : '') + (!node.publicId && node.systemId ? ' SYSTEM' : '') + (node.systemId ? ' "' + node.systemId + '"' : '') + ">";

    return doctype_string === '<!DOCTYPE html>';
};

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM