2011-04-18 78 views
0

我正在编写一个网页,当用户单击某个按钮时,我需要显示带有某些内容的div。 我写了下面的代码,我不明白为什么它不起作用。 有人知道为什么吗?当用户点击按钮时显示div元素的问题

我的代码:

<html> 
    <head> 
    <meta http-equiv="Content-Type" content="text/html; charset=iso 8859-1" /> 

    <script type="text/javascript"> 

    function traverse(){ 
     output.innerHTML+='Test'; // Nothing happens ! 
    } 

      function check() { 
      var keywords = document.getElementById('text').value.split(" "); 

      for (var i=0; i < keywords.length; ++i) { 
       traverse_tree()  
      } 
      } 


    </script> 


    </head> 
    <body onload ="init()"> 
     <input id="text" type="text" size="60" value="Type your keywords here" /> 
     <input type="button" value="Display the text 'Test'" onclick="check();" />  

     <div id="output"> 
     </div> 

    </body> 
    </html> 

感谢,

布鲁诺

回答

5

也许是因为函数被调用traverse()和你打电话traverse_tree()

+0

感谢。我真的很惭愧:-(lol – Bruno 2011-04-18 10:37:16

+1

不要,我做了很多次类似的事情,很容易犯这样的错误。 – geekchic 2011-04-18 10:37:59

0

而且,在你的方法traverse,你应该使用document.getElementById('output'),而不是使用(未定义)可变output获得元素:

即:

function traverse(){ 
    document.getElementById('output').innerHTML+='Test'; 
} 

您也可以通过缓存加速此所述节点(避免调用的getElementById每个按钮被点击时):

// Create a closure by wrapping the cached node in a self-executing 
// function to avoid polluting the global namespace 
var traverse = (function (nodeId) { 

    // Cache the node to be updated here 
    var node = document.getElementById(nodeId); 

    // This is the function that "traverse()" will call. Return this function, 
    // which will assign it to the variable traverse. 
    return function() { 
    node.innerHTML += 'test'; 
    }; 

// Execute the function with the id of the node to cache, i.e. output 
}('output')); 
相关问题