问题
Is it possible to use document.writeln when trying to create a nested list? I am at the very very basic of learning javascript and don't know what I am doing wrong. I need to create a nested list using document.writeln, which seems to work. But, when I try to get it verified, a get a bunch of errors and it doesn't seem to be valid. Is it even possible to do what I am doing. For example. I have in the head (in the script area) something like:
var number1 = {"Name": "Smith", "First Name": "John", "Number": "58"};
and in the script area in the body I have:
document.writeln("<ul>");
document.writeln("<li>" + "Individual : ");
document.writeln("<ul>");
for (x in number 1) {
document.writeln("<li>" + number1[x] + "</li>");}
}
document.writeln("</li></ul></ul>");
回答1:
Well, this line is wrong:
document.writeln("</li></ul></ul>");
That should be:
document.writeln("</ul></li></ul>");
EDIT: You've also got an extra closing brace:
for (x in number 1) {
document.writeln("<li>" + number1[x] + "</li>");} // Remove the extra } here
}
So the test content I'm using is:
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"
"http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="content-type" content="text/html; charset=iso-8859-1" />
<title>Test</title>
<meta name="description" content="asdf" />
<script type="text/javascript">
var number1 = {"Name": "Smith", "First Name": "John", "Number": "58"};
</script>
</head>
<body>
<h2>asdf</h2>
<script type="text/javascript">
//<![CDATA[
document.write("<ul>");
document.write("<li>" + "Individual : ");
document.write("<ul>");
for (x in number1) {
document.write("<li>" + number1[x] + "<\/li>");
}
document.write("<\/ul><\/li><\/ul>");
//]]>
</script>
</body>
</html>
Example now validates and works.
回答2:
The space between number and 1 in for (x in number 1)
makes this invalid JavaScript. Also, the order of closing elements is wrong;
document.writeln("</li></ul></ul>");
should be
document.writeln("</ul></li></ul>");
However, it is not a good idea to use document.writeln
in general, especially when the input (number1
in your case) can be influenced by the user. For example, take the following input:
var number1 = {"Name": "Smith<h1>"};
This input will result in the layout of your site being broken. In general, directly writing user input with document.writeln
allows users of your website to deface it and hijack other user's cookies by exploiting the Cross-site scripting vulnerability.
Instead of using document.write
, use the DOM and/or jQuery.
来源:https://stackoverflow.com/questions/6641389/is-it-possible-to-use-document-writeln-using-javascript-when-trying-to-create