inside of a javascript function, i.e.,inside of a "while", can i put somehow a button or a link that changes according with some variable inside the loop?
Announcement
Collapse
No announcement yet.
put links inside of a function?
Collapse
X
-
-
for example,
function sample(array)
{
var i = 0;
while (i < array.length)
{
document.write("Value: " + array[i] );
<a href="" onClick="newfunction(array[i]);"> <br> dosomething </a>'
--->> How can I write this line in a JS function?
i++;
}
}
Comment
-
Do you want to modify an existing link or create a new one on the fly? When do you want to create a link? As the page loads or after some events like onlick? More details please...
Comment
-
like this?
Code:<html> <head> <script type="text/javascript"> var arr = new Array("item1","item2","item3"); function createLinks(){ var str=''; for (var i=0;i<arr.length;i++){ str+='<a href="#" onclick="newfunction(\\''+arr[i]+'\\');return false">do something</a><br>'; } document.getElementById('linkContainer').innerHTML=str; } function newfunction(str){ alert(str) } </script> </head> <body> <form> <input type="button" value="Create Links" onclick="createLinks()"> <div id="linkContainer"></div> </form> </body> </html>
Comment
-
Thanks. I think that is what I wanted.
I'm trying to apply it, but what's wrong whith this code?
<script language = "JavaScript">
var array = new Array(1,2,3,4,5);
var result = new Array(1,3);
function show_Results(result)
{
var str='';
for (var i = 0;i < result.length;i++)
{
document.write("<br>" + "Index position: " + result[i]);
document.write("<br>" + array[result[i]].info + "<br>");
str+='<a href="#" onclick="newfunction(\''+result[i]+'\');return false">do something</a><br>';
}
document.getElementById('linkContainer').innerHTML=str;
}
function newfunction(str)
{
alert("");
}
</script>
<input type="button" value="Test" onclick="show_Results(result)">
<div id="linkContainer"></div>
-----
Comment
-
Remove the 2 document.write statements as these will overwrite the whole page. If you really need them and not for debugging purposes only, then the code should be like this:
Code:var array = new Array(1,2,3,4,5); var result = new Array(1,3); function show_Results(result) { var str=''; for (var i = 0;i < result.length;i++) { str+='<br>Index position: ' + result[i]; str+='<br>' + array[result[i]] + '<br>'; str+='<a href="#" onclick="newfunction('+result[i]+');return false">do something</a><br>'; } document.getElementById('linkContainer').innerHTML=str; } function newfunction(num) { alert(num); }
And what's with array[result[ i ]].info? The variable array is an array of numbers not array of objects.Last edited by glenngv; Feb 10, 2004, 12:30 AM.
Comment
-
onload
<body onload="show_Results(result)">
or inside the script tag:
window.onload=function(){show_Results(result)};
Comment
Comment