2012-05-10 49 views
0

我正在尝试编写一个简单的脚本。用javascript更改文本

这里的理念是:

我有一个div元素和内格动态创建的段落元素。段落元素包含一些文本。我也在页面上有一个链接。点击链接时,我希望文字更改为其他文字(预定义)。我有2个功能:一个用于创建段落元素并将其附加到div的功能。第二个功能是改变文字。我认为问题已经是与从一个函数传递变量到另一个

这里是HTML:

<a href='' onclick='changeText();return false;'>Change Text</a> 

    <div id='box'></div> 

这里是JS代码:

var x = document.getElementById('box'); 

     window.onload = function createEl(){ 

      var p = document.getElementsByTagName('div')[0]; 
      var el = document.createElement('p'); 

       var text = "Hello"; 
       p.appendChild(el); 
       var res = document.createTextNode(text); 
       el.appendChild(res); 
} 


function changeText(){ 

    text.innerHTML = 'other text'; 


} 

回答

0

你正确之嫌。然而,我并没有解决脚本中出现错误的地方(因为你犯了几个初学者的错误),而是稍微改写了它,并解释了每件事情在做的时候的作用。这里有一个你应该工作的脚本版本:

// we define these variables outside of any functions 
// this means they're global and any function can get 
// access to them. 
var box_div, el; 

window.onload = function createEl() { 
    // get references to div element 
    box_div = document.getElementById('box'); 

    // create a new <p> element and store it in 'el' 
    el = document.createElement('p'); 

    // add text to the new <p> element 
    el.appendChild(document.createTextNode("Hello")); 

    // append the new <p> element to the div 
    box_div.appendChild(el); 
} 

function changeText() { 
    // since we have a reference to the <p> element 
    // already, we can just do this: 
    el.innerHTML = 'other text'; 
}​