2012-05-10 47 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'; 
}​