Javascript doesn't change document?
Take a look at this example code, which doesn't work:
<?xml version='1.0' encoding='UTF-8' ?>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD开发者_JS百科/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<script type="text/javascript">
<!--
function moveMe() {
document.getElementById('moveme').top = 200;
document.getElementById('moveme').style.backgroundcolor = 'green';
document.getElementById('writeme').innerHtml = 'abc';
alert('called!');
}
// -->
</script>
<style type="text/css">
.moveable {
position: absolute;
top: 30px;
left: 200px;
width: 100px;
height: 100px;
background-color: yellow;
}
#writeme {
background-color: red;
color: white;
}
</style>
</head>
<body>
<div id="moveme" class="moveable" onClick="moveMe()">
<p id="writeme">Hello!</p>
</div>
</body>
</html>
When I click on the text the alert is displayed, but nothing is changed in the document. The paragraph text is not overwritten, the div is not moved... tested it in FF and IE, also checked the DOM via Firebug: strange thing is that the new values are written to the nodes, but they are displayed in bold, and the old values are still there. WTF?
I guess I'm missing something fundamental here.
- Non-zero lengths require units, "200" is missing its unit
- JavaScript is case sensitive:
backgroundColor
andinnerHTML
- Since you appear to be using XHTML, your script is commented out
document.getElementById('moveme').top = 200;
needs to be
document.getElementById('moveme').style.top = "200px";
I think; and
document.getElementById('writeme').innerHtml = 'abc';
needs to become
document.getElementById('writeme').innerHTML = 'abc';
and it's backgroundColor
with a capital C as @David spotted first.
Try this:
<script type="text/javascript">
function moveMe() {
document.getElementById('moveme').style.top = '200px';
document.getElementById('moveme').style.backgroundColor = 'green';
document.getElementById('writeme').innerHTML = 'abc';
alert('called!');
}
window.onload = moveMe;
</script>
Additionally to what the others said: Drop the <?xml version='1.0' encoding='UTF-8' ?>
, because that puts IE in Quirksmode.
精彩评论