简体   繁体   中英

How to get click event object data from dynamically created button using JQuery or javascript

I am collecting page button click events. Normally i am collecting the objects from statically created DOM elements. By using,

 $('input[type=button]').each(function () {
              $(this).bind('click', function () {
                  Console.log(this);
              });
          });

But when i add a new button dynamically like,

 vvar newBtn = document.createElement('input');
      newBtn.type = 'button';
      newBtn.setAttribute('id', 'JgenerateBtn');
      newBtn.setAttribute('value', 'JgenerateBtn');
      newBtn.onclick = function () { alert('javascript dynamically created button'); };
      var holderDiv = document.getElementById('holder');
      holderDiv.appendChild(newBtn);

after this code, New Button is created and event also triggering, But i cant able to get the Event object by using, same above code.

 $('input[type=button]').each(function () {
          $(this).bind('click', function () {
              Console.log(this);
          });
      });

Please provide suggestion to get the dynamically created elements event object.

You may use on() for binding events on dynamically added elements. Like this:

$(document).on('click', 'input[type=button]', function(){
    console.log(this);
});

This is just for simple example, it is better to bind it on element closer to your button that is already on page when it first loads rather than on document .

You should use the following:

// New way (jQuery 1.7+) - .on(events, selector, handler)
$('#holder').on('click', ':button', function(event) {
    alert('testlink'); 
});

This will attach your event to any button within the #holder element, reducing the scope of having to check the whole document element tree and increasing efficiency.

More info here:-

The event object is handed to your click handler as the first argument.

$('input[type=button]').each(function () {
    $(this).bind('click', function (event) {
        Console.log(event);
    });
});

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM