javascript 为什么我会收到这个 jsfiddle 错误,document.write 可以是 eval 的一种形式

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/15048194/
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-26 23:17:53  来源:igfitidea点击:

Why am i receiving this jsfiddle error, document.write can be a form of eval

javascriptjsfiddle

提问by lboyel

I am testing a code I found while reading a book. I get this error while testing it out in JS fiddle, document.writecan be a form of eval.

我正在测试我在阅读一本书时发现的代码。我在 JS fiddle 中测试时遇到此错误,document.write可能是 eval 的一种形式。

     var text = '<html><body bgcolor=linen><p>' +
    'This is <b>bold<\/b>!<\/p><\/body><\/html>';

var tags = /[^<>]+|<(\/?)([A-Za-z]+)([^<>]*)>/g;
var a, i;
while ((a = tags.exec(text))) {
    for (i = 0; i < a.length; i += 1) {
        document.writeln(('// [' + i + '] ' + a[i]).entityify());
    }
    document.writeln();
}   

I am getting the above JSfiddle warning on both lines with document.writeln().

我在两行都收到了上面的 JSfiddle 警告document.writeln()

回答by ziesemer

Note that this is a warning only - but a good one that should be respected. It is actually being generated by a checker called JSLint- and a good read for the reasoning of this warning is available at http://www.jameswiseman.com/blog/2011/03/31/jslint-messages-document-write-can-be-a-form-of-eval/.

请注意,这只是一个警告 - 但应该受到尊重。它实际上是由一个名为JSLint的检查器生成的- 可以在http://www.jameswiseman.com/blog/2011/03/31/jslint-messages-document-write- can-be-a-form-of-eval/

Basically, the foundation of this is that "eval is evil" - and that document.writecan be used to perform evaluations.

基本上,其基础是“ eval 是邪恶的” -document.write可用于执行评估。

Besides this - and not mentioned in the above, avoid document.writewhenever possible, except for maybe simple testing. It writes to the DOM after it is considered to be "complete", and modifications at this point should only be made using the supported DOM methods. Additional details concerning this are covered at Why is document.write considered a "bad practice"?- where it is mentioned that it is "Far better to use the safe and DOM friendly DOM manipulation methods" (document.createElement, element.appendChild, etc.). A good concrete example of this is available at https://developer.mozilla.org/en-US/docs/Web/API/Document_object_model/Using_the_W3C_DOM_Level_1_Core.

除此之外 - 上面没有提到,document.write尽可能避免,除了简单的测试。它在被认为“完成”后写入 DOM,此时只能使用支持的 DOM 方法进行修改。关于此的其他详细信息在为什么 document.write 被视为“不良做法”?-在那里提到的是“远不如使用安全和DOM友好的DOM处理方法”( ,document.createElementelement.appendChild等)。https://developer.mozilla.org/en-US/docs/Web/API/Document_object_model/Using_the_W3C_DOM_Level_1_Core提供了一个很好的具体示例。