2013-02-25 190 views
0
for (var i=0;i<x.length;i++) 
{ 
    var Topic = x[i].getElementsByTagName("text")[0].childNodes[0].nodeValue; 
    var Content = x[i].getElementsByTagName("description")[0].childNodes[0].nodeValue; 
    document.write("<li class='withimage'> "); 
    document.write(Topic); 
    document.write("<button onclick='show(Topic)'></button>"); 
    document.write("</span><span class='time'>"); 
    var full_time = x[i].getElementsByTagName("created_at")[0].childNodes[0].nodeValue; 
    var time = full_time.split("+"); 
    document.write(time[0]); 
    document.write("</span></li>"); 

    } 

我的功能是JavaScript:如何從for循環將變量傳遞給JS函數?

function show(head) 
{ 
document.getElementById("content").style.display="none"; 

document.getElementById("details").style.display="block"; 

document.getElementById("Heading").innerHTML=head; 
} 

但每個按鈕單擊我的變量「主題」最終的迭代值

+1

由於取值爲Topic'是 「硬編碼」 在此這一行:'文件撰寫(「<按鈕的onclick = '秀(主題)'>「);' – marekful 2013-02-25 10:46:56

+0

在javascript中關閉。閱讀它 – 2013-02-25 10:49:17

+0

要真正解決您的問題,您必須至少使用傳統事件處理程序,而不是內聯事件處理程序,以便您使用閉包(與[此解決方案]結合使用)(http://stackoverflow.com/questions/ 750486/javascript-closure-inside-loops-simple-practical-example)),而不是像你的情況那樣使用全局變量。更多信息:http://www.quirksmode.org/js/introevents.html。 – 2013-02-25 10:52:29

回答

0

這裏的問題是,你沒有通過Topic對象爲每按鈕。其實你只是傳遞對象名稱。所以當你點擊任何按鈕時,它將搜索變量Topic,在這種情況下,這將是迭代中最後一個Topic對象。

您嘗試這樣的:

for (var i=0;i<x.length;i++) 
{ 
    var Topic = x[i].getElementsByTagName("text")[0].childNodes[0].nodeValue; 
    var Content = x[i].getElementsByTagName("description")[0].childNodes[0].nodeValue; 
    document.write("<li class='withimage'> "); 
    document.write(Topic); 
    document.write("<button onclick='show(" + Topic + ")'></button>"); 
    document.write("</span><span class='time'>"); 
    var full_time = x[i].getElementsByTagName("created_at")[0].childNodes[0].nodeValue; 
    var time = full_time.split("+"); 
    document.write(time[0]); 
    document.write("</span></li>"); 

    }