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>");

  }

My function is

function show(head)
{
document.getElementById("content").style.display="none";

document.getElementById("details").style.display="block";

document.getElementById("Heading").innerHTML=head;
}

But in every button click I got the final iterating value in the variable "Topic"

Ebin Sebastian
  • 1,291
  • 1
  • 13
  • 15
  • 1
    Because the value `Topic` is "hard-coded" in this this line: ` document.write("");` – marekful Feb 25 '13 at 10:46
  • closures in javascript. read it – Sudip Pal Feb 25 '13 at 10:49
  • To really fix your problem, you have to use at least traditional event handlers, not inline event handlers, so that you make use of closures (in combination with [this solution](http://stackoverflow.com/questions/750486/javascript-closure-inside-loops-simple-practical-example)) and not use global variables, like in your case. More info: http://www.quirksmode.org/js/introevents.html. – Felix Kling Feb 25 '13 at 10:52

1 Answers1

0

The problem here is that you are not passing the Topic Object for each button. Actually you are passing just the object name. So when you click on any button it 'll search for the variable Topic which in this case 'll be the last Topic object in your iteration.

you try something like this :

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>");

  }
ebram khalil
  • 8,252
  • 7
  • 42
  • 60