2013-02-25 193 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>"); 

    }