html - Javascript - Dynamically assign onclick event in the loop -


i have simple html page js code:

<html>     <head>         <title></title>     </head>     <body>          <div id="divbuttons">          </div>          <script type="text/javascript">             var arroptions = new array();              (var = 0; < 10; i++) {                 arroptions[i] = "option" + i;             }              (var = 0; < arroptions.length; i++) {                 var btnshow = document.createelement("input");                 btnshow.setattribute("type", "button");                 btnshow.value = "show me option";                 var optionpar = arroptions[i];                 btnshow.onclick = function() {                     showparam(optionpar);                 }                  document.getelementbyid('divbuttons').appendchild(btnshow);             }              function showparam(value) {                 alert(value);             }                 </script>     </body> </html> 

that page binds 10 buttons, when click on button shows alert "option9". how possible assign onclick event show correspondent option !?

thanks!

you'll have this:

btnshow.onclick = (function(opt) {     return function() {        showparam(opt);     }; })(arroptions[i]); 

Comments

Popular posts from this blog

apache - Add omitted ? to URLs -

redirect - bbPress Forum - rewrite to wwww.mysite prohibits login -

php - How can I stop spam on my custom forum/blog? -