当前位置: 动力学知识库 > 问答 > 编程问答 >

javascript - Working on jsfiddle.net but not on my Laptop?

问题描述:

Kindly look at http://jsfiddle.net/fLd5T/.

This simple javaScript code running fine on jsfiddle.net is not working on my laptop.

Here is the code on my laptop:

<HTML>

<HEAD>

<script type="text/javascript">

// setup

var goal = "fix the bug";

var date2 = new Date();

var diff = 0;

var active = true;http://jsfiddle.net/#save

var data = '{"goals": [{"goal":"' + goal + '","duedate":"'

+ date2 + '","noofdays":"' + diff + '","active":"'

+ active + '"}]}';

localStorage.setItem("goals",data);

// test

var goalsStr = localStorage.getItem("goals");

var goalsObj = JSON.parse(goalsStr);

for (i=0; i<goalsObj.goals.length; i++) {

//if(goal==goalsObj.goals[i].goal) {

document.body.appendChild(document.createTextNode(

"The goal is " + JSON.stringify(goalsObj.goals[i])));

}

}

</script>

</HEAD>

<BODY>

</BODY>

</HTML>

javaScript is enabled in my browser.

Why is it so? What's wrong? What should I do?

网友答案:

When I check your code I see 2 things:

First at line 18 the if statement is commented out, but the closing } is not which leads to a syntax error.

The other thing is that you're trying to access document.body before it's been created. You should move your javascript code (the entire <script>...</script>) inside <body></body> instead of <head></head>.

You can also add window.onload = function () { ... } around your javascript code.
It's working on jsfiddle because that's what it's actually done there.

分享给朋友:
您可能感兴趣的文章:
随机阅读: