0

I have a large number of buttons in my page and i want to add a click event to each of the buttons , that is when the user click the buttons it shows the corresponding button value.

i have already implement a method with the help of anonymous functions. i have included my code below

HTML

<div id="div1"/>

Javascript

$(document).ready(function(){
    for(var i =0;i<100;i++)
    {
        $("#div1").append("<input type='button' class='myclass' id='mybutton" + i + "' value='mybutton" + i + "'> ");
    };

    $(".myclass").click(function(e){
        alert(e.target.id);
    });
});

It is working perfectly, the problem is an anonymous function is created for each button on this Form, that is if i have 10k elements in my page then anonymous function will created 10k times, i think i causes big memory wastage. Is there any better way for achieving this ? please help me to solve this , any help will be greatly appreciated . Thanks

3 Answers3

0

I think you can use use event delegation For solving this problem .

event delegation is a mechanism of responding to ui-events via a single common parent rather than each child.

More about event Delegation you can refer this stack overflow question

In you case it is better to use event delegation

You can use the following code

$(document).ready(function(){
    for(var i =0;i<100;i++)
    {
        $("#div1").append("<input type='button' class='myclass' id='mybutton" + i + "' value='mybutton" + i + "'> ");
    }
    $("#div1").click(function(e){
        if($(e.target).hasClass("myclass"))
           alert(e.target.id);
    });    
});

You can check this I have included a example with this DEMO

Or You can Adopt Chris's Solutions, it will also works fine

Community
  • 1
  • 1
Arunprasanth K V
  • 17,147
  • 8
  • 33
  • 63
0

You want jQuery's on function, along these lines...

$("#containerdiv").on('click', '.myclass', function() {
    alert($(this).id);
});
ChrisV
  • 1,289
  • 8
  • 14
0
$(document).ready(function(){
 var callback=function(){
            console.log(this.id);   
    } ;
$('#div1').on('click','button.myclass',callback);
    for(var i =0;i<100;i++)
    {
        $("#div1").append("<input type='button' class='myclass' id='mybutton" + i + "' value='mybutton" + i + "'> ");
    };


});      






this is called event delegation.
Pushker Yadav
  • 776
  • 1
  • 6
  • 14