[英]JavaScript: How do I pass a variables in to a JS function, from a for loop?
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
,在這種情況下,它將成為迭代中的最后一個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>");
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.