【问题标题】:JavaScript: How do I pass a variables in to a JS function, from a for loop?JavaScript:如何从 for 循环将变量传递给 JS 函数?
【发布时间】: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


【解决方案1】:

这里的问题是您没有为每个按钮传递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>");

  }

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2021-05-31
    • 1970-01-01
    • 2019-08-13
    • 2013-10-25
    • 1970-01-01
    • 1970-01-01
    • 2014-10-05
    • 1970-01-01
    相关资源
    最近更新 更多