tinfanide Posted May 19, 2011 Share Posted May 19, 2011 My two questions are embedded within the code below:The scripts outside the comments works fine. I want to ask for more of why the scripts within the comments work the way I didn't expect, though.For question 1:If I use innerHTML in this case, it seems that I do not have to use for in. I don't even have to loop through the array, just by simply writing like text.innerHTML = txt; and the thing is done.Is there anything wrong with my use of for in here?For question 2:I wonder how appendChild & createTextNode are different from innerHTML in this case.It works (click and show up the text ONCE only) with innerHTMLbutnot appendChild.Another question there is:I want to click the button to show the text ONCE and for all with appendChild. How can I achieve that effect in JS?Please take a look. Thank you. <input type="button" value="Click to see what happens!" id="click" /><br /><div id="text"></div><script>var click = document.getElementById("click");var text = document.getElementById("text"); var txt = new Array (3); txt[0] = "I have two cats!"; txt[1] = "I feed them every day!"; txt[2] = "I play with them every evening!"; click.onclick = function(){for (x in txt) { text.innerHTML = txt.join("<br />"); /* text.innerHTML = txt[x]; // why only txt[2] appears? */ /* text.appendChild( document.createTextNode(txt[x]) ); text.appendChild( document.createElement('br') ); // how can I make the click function work only ONCE with appendChild? */ } };</script> Link to comment Share on other sites More sharing options...
Ingolme Posted May 19, 2011 Share Posted May 19, 2011 The reason is that you keep assigining a new value to text.I don't like using the for...in loop because it also includes properties such as "length".You would do better with something like this: var str = ""; // Empty stringfor( conditions ) { str += somevalue // Append the array element value to the string}text.innerHTML = str; If you want to check if the button or link was clicked already just set a global variable to true when the event fires the first time: var clicked = false;click.onclick = function(){ if(clicked) { return; } else { clicked = true; // The button was clicked } // Do something} Link to comment Share on other sites More sharing options...
Recommended Posts
Archived
This topic is now archived and is closed to further replies.