简体   繁体   中英

Bind function on Runtime for dynamically created html element

I have to dynamically create a <ul> html element with a specific class, say class_c , using an ajax call.

class_c is used by a third party js file, which can neither be changed nor called manually as it is anonymous (like $('.class_c').click(function(e){}) ) so I can't bind using jQuery .bind() .

Is there a way to rebuild the binding for all the elements with class_c , so that the new element can respond to this anonymous function?

if you use on() instead of click(), you can bind the click handle to all child elements of your selector, even if those elements will be created in future. of course, you then need a container for those "to be created elements", that is already in the dom, or the handler still won't work...

$('.myContainer').on("click", ".class_c", function(e){});

If you mean you want to fire their handler, for new elements you add they they haven't hooked the event on, then other than hacking jQuery internals the only thing I can come up with is cloning one of the elements they've hooked the event on.

jQuery's clone method accepts an argument that tells it to clone events and data as well as just the node. So when adding the new element, you could do this:

var clone = $(".class_c").first().clone(true);
clone.html(/*...your content here...*/);
clone.appendTo(/*...some appropriate target...*/);

Live Example

<!DOCTYPE html>
<html>
<head>
<script src="//code.jquery.com/jquery-1.11.0.min.js"></script>
  <meta charset="utf-8">
  <title>Example</title>
</head>
<body>
  <ul class="class_c">
    <li>Original - click me!</li>
  </ul>
<script>
  (function() {
    "use strict";

    // "Other" code hooks click on .class_c elements by *cloning* one of
    // the ones that already has the click event hooked, using the `true`
    // argument that tells jQuery to clone event handlers and data
    $(".class_c").click(function() {
      display("Handler triggered for '" + $(this).text() + "'");
    });

    // Your code adds a new .class_c element
    var clone = $(".class_c").first().clone(true);
    clone.html("<li>Clone - click me!</li>");
    clone.appendTo(document.body);

    function display(msg) {
      var p = document.createElement('p');
      p.innerHTML = String(msg);
      document.body.appendChild(p);
    }
  })();
</script>
</body>
</html>

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