JavaScript:如何将变量从for循环传递到JS函数?
但是在每次单击按钮时,我都会得到变量“Topic”中的最终迭代值。这里的问题是,您没有为每个按钮传递JavaScript:如何将变量从for循环传递到JS函数?,javascript,function,variables,for-loop,Javascript,Function,Variables,For Loop,但是在每次单击按钮时,我都会得到变量“Topic”中的最终迭代值。这里的问题是,您没有为每个按钮传递Topic对象。实际上,您只传递了对象名。因此,当您单击任何按钮时,它将搜索变量Topic,在本例中,该变量将是迭代中的最后一个Topic对象 您可以尝试以下方式: function show(head) { document.getElementById("content").style.display="none"; document.getElementById("details").st
Topic
对象。实际上,您只传递了对象名。因此,当您单击任何按钮时,它将搜索变量Topic
,在本例中,该变量将是迭代中的最后一个Topic
对象
您可以尝试以下方式:
function show(head)
{
document.getElementById("content").style.display="none";
document.getElementById("details").style.display="block";
document.getElementById("Heading").innerHTML=head;
}
for(var i=0;ibe因为Topic
在这一行中是“硬编码”的:`document.write(“”;`closures in javascript.read itt要真正解决您的问题,您必须至少使用传统的事件处理程序,而不是内联事件处理程序,以便使用闭包(与)不要使用全局变量,如您的情况。详细信息:。
function show(head)
{
document.getElementById("content").style.display="none";
document.getElementById("details").style.display="block";
document.getElementById("Heading").innerHTML=head;
}
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>");
}