2011-11-29 130 views
0

如果有人愿意帮忙,我需要帮助。我无法得到2 getElementById函数的工作,我是一个初学者,所以我相信这是简单的,但我一直无法解决它。我需要点击文字才能更改字体。任何帮助正确的方向将非常感谢。请检查下面的代码。JavaScript getElementById not Working

<?xml version = "1.0" encoding = "utf-8"?> 
    <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" 
     "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd"> 
<html xmlns = "http://www.w3.org/1999/xhtml"> 

<head> 
     <title>Solution Page 486 Exercise 12.7</title> 
    <style type = "text/css"> 
      .option { color: darkblue } 
      .graybg { background-color: #aaaaaa } 
      .whitebg { background-color: #ffffff } 
      .sans { font-family: sans-serif } 
      .serif { font-family: serif } 
     </style> 
<script type = "text/javascript"> 
      function bodyClass(color) 
      { 
       document.body.className = color; 
      } 

     </script> 
    </head> 

    <body> 
     <div id = "main">Click on Options Listed Below to see how they modify this page.<br ><br > 
      <div>Options: 
      <div onclick = "bodyClass('graybg');" 
       class = "option">Gray background</div> 
       <div onclick = "bodyClass('whitebg');" 
       class = "option">White background</div> 
      <div onclick = "document.getElementById(" class 
       = "option" classname ="sans" ? main?).>Sans-serif text</div> 
      <div onclick = "document.getElementById(" class 
       = "option" classname ="serif" ? main?).>Serif text</div></div></div> 
    </body> 
</html> 
+0

你的标记都搞砸了。 ''div onclick =“document.getElementById('YOUR_ID_HERE')”....>'它应该是怎么样的 – JohnP

+0

getElementById就是这样,它会通过它的ID获得一个元素,例如document.getElementById(“main” )然后会像上面那样获得id =“main”的div。 – Matt

回答

1

不要在分配给'onclick'属性的字符串中编写JavaScript。写在一个标签的功能,并分配功能,这里是代码:

<body> 
... 
<div id='an_id'> <!-- doesn't have to be a div, any element is OK --> 
... 
<script type='text/JavaScript'> 
    var some_elem = document.getElementById('an_id'); 
     some_elem.onclick = my_func; // no parens, no quotes! 

    function my_func() { 
     // your code goes here 
     // in here, 'this' refers to the element that got the click 
    } 
</script> 

</body> 

希望这会有所帮助。

1

getElementById语法是:

document.getElementById('the_id_of_an_element') 

您有:

document.getElementById(

你需要给它一个参数,包括关闭)。那么你可能想用返回值做一些事情。

1

的document.getElementById本身说,它的编号而不是由类或任何其他属性获取元素,这应该工作document.getElementById('main')

0

你不明白的getElementById是如何工作的:

<html> 
<head> 
    <script type="text/javascript"> 
    function onButtonClick() {{ 
     document.getElementById("main").innerHTML = "html of div main has changed!"; 
    }; 
    </script> 
</head> 
<body> 
    <div id="main">This is the initial text</div> 
    <button onclick="onButtonClick();">Click me</button> 
</body> 
</html> 

保存以上代码为“test.html”,在浏览器中加载它,点击按钮,看效果。

<div id="main"> < = id =“main”意味着您给“div”元素赋予标识符,当您调用“document.getElementById”时,需要传递“id”的值,在这种情况下为“main ”。