简体   繁体   中英

Attach event listener to dom fragment

I want to attach "onchange" event listener to a dom fragment but it's not working properly.

For example I have the following code:

$(function(){
  var elements = [
    '<input type="checkbox" name="one" value="kung" />',
    '<input type="checkbox" name="one" value="fu" />'
  ];

  var fragment = $(document.createDocumentFragment());

  fragment.on('change', 'input[type="checkbox"]', function(){
    alert('my kung fu is strong');
  });

  $.each(elements, function(index, element){
    fragment.append(element);
    fragment.find('input:last-child').trigger('change');
  });
});

However the attach event listener is not working. But if I attach the event handler in the loop like this it will work:

fragment.find('input[type="checkbox"]').on('change', function(){
  alert('this works, but it is not ok');
});

I do not want to set the event listener in the loop as I feel it will slow down the script and it's an overkill.

Also I need to mention that my array of of elements is quite big.

Document fragments don't have addEventListener or similar. They're a subinterface of Node that also implement ParentNode , but not EventTarget .

Your options are:

  1. Attach the handlers directly to the input s (which you've said you don't want to do), or

  2. Add a top-level container element to the fragment that contains the input s, and put the event handler on that instead.

  3. Attach the handler to the document you add the document fragment to (if your code is involved in that)

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