Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
242 views
in Technique[技术] by (71.8m points)

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

I am testing a code I found while reading a book. I get this error while testing it out in JS fiddle, document.write can be a form of 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().

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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/.

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

Besides this - and not mentioned in the above, avoid document.write whenever 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.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...