【发布时间】:2013-02-25 10:45:06
【问题描述】:
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>");
}
我的功能是
function show(head)
{
document.getElementById("content").style.display="none";
document.getElementById("details").style.display="block";
document.getElementById("Heading").innerHTML=head;
}
但是在每次点击按钮时,我都会在变量“Topic”中得到最终的迭代值
【问题讨论】:
-
因为值
Topic在此行中是“硬编码”的:` document.write("");` -
javascript 中的闭包。阅读它
-
要真正解决你的问题,你必须至少使用传统的事件处理程序,而不是内联事件处理程序,这样你就可以使用闭包(结合this solution)而不是使用全局变量,就像你的情况一样。更多信息:quirksmode.org/js/introevents.html.
标签: javascript function variables for-loop