简体   繁体   中英

attach event to dynamic element

Hey im having a problem attaching an event to an element im dynamically generating. I would appreciate any advice on solving the issue im not sure whether its the method that im using to attach the event or whether its something else:

for (var i = 0; i < array.length; i++) { 
itemlist=itemlist.concat('<pre'+' id="pres'+i+'"'+'>'+array[i]+'</pre>');

var name = '#pres'+i;
$( name ).click(function() {
  alert( "Handler for .click() called." );
});
}

I also tried this method which i found on stack overflow however yielded no result :

var name = '#pres'+i;
$(name).on('click', function() {
    alert( "Handler for .click() called." );
});

Whilst inspecting in chrome all of the elements exist with the correct ID, however the jquery event i have attached does not perform its alert. I have looked at some solutions however i do not want to attach the same function to all "" tags however attaching the same event to each of the ones in the loop would be acceptable. Any help would be appreciated :)

Instead of generating unique id attributes, which makes the code needlessly more complex and can be a pain to maintain, you could instead use a single common class and attach a single delegated event handler to all the elements. Try this:

$('#myContainer').on('click', '.foo', function() {
    // handle the element click here...
    console.log($(this).text());
});

var html = '';
for (var i = 0; i < array.length; i++) { 
    html += '<pre class="foo">' + array[i] + '</pre>';
}
$('#myContainer').append(html);

Rory McCrossan's answer is the simplest way to do it if you just add the elements at the beginning and set their .click after that.
However, if you call the generating function sometime later than that, I'd suggest using something like this, a function that sets the .click event handler for each element when it is created.

You can still have your IDs and so on, you just don't really need them.

  var itemlist=[] var array=["Element 1","Element 2","Element 3"] for (var i = 0; i < array.length; i++) { element=$('<pre' + ' id="pres' + i + '"' + '>' + array[i] + '</pre>'); $(element).click(function () { alert("Handler for .click() called."); }); itemlist.push(element); } $("body").append(itemlist) 
 <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> 

You need to use the on method in the container that contains all pre elements, like code bellow.

Suppose you have this result:

<div class="container-pre">
  <pre id="pres1" data-id="1" class="pre-element">Some text 1</pre>
  <pre id="pres2" data-id="2" class="pre-element">Some text 2</pre>
  <pre id="pres3" data-id="3" class="pre-element">Some text 3</pre>
</div>

Then your jQuery configuration would like this:

$(document).ready(function() {
  $(".container-pre").on("click", ".pre-element", function(e) {
        var elem = $(e.currentTarget);
        var id = elem.attr("data-id");
        alert( "Handler for .click() called at element " + id);
    });
});

You can see this plunker with this code in action:

https://embed.plnkr.co/v61GxazfsT8RscuMTxI9/

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