Wednesday, 11 October 2017

javascript - jQuery how to bind onclick event to dynamically added HTML element





I want to bind an onclick event to an element I insert dynamically
with jQuery




But It never runs the
binded function. I'd be happy if you can point out why this example is not working and
how I can get it to run properly:



data-lang="js" data-hide="false" data-console="true"
data-babel="false">

class="snippet-code-html lang-html prettyprint-override"> html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"

"http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
xmlns="http://www.w3.org/1999/xhtml" xml:lang="da" lang="da">


test of click<br /> binding


src="https://code.jquery.com/jquery-1.12.4.min.js">





Test of click binding



problem: to bind a click event to an element I append via
JQuery.



class="add_to_this">

The link is created, then added
here below:




class="add_to_this">

Another is added here
below:














EDIT:
I edited the example to contain two elements the method is inserted to.

In that case, the alert() call is never executed. (thanks to
@Daff for pointing that out in a comment)


class="post-text" itemprop="text">
class="normal">Answer



The first
problem is that when you call append on a jQuery set with more than one element, a clone
of the element to append is created for each and thus the attached event observer is
lost.



An alternative way to do it would be to
create the link for each
element:




function
handler() { alert('hello'); }
$('.add_to_this').append(function() {

return $('Click
here
').click(handler);
})


Another
potential problem might be that the event observer is attached before the element has
been added to the DOM. I'm not sure if this has anything to say, but I think the
behavior might be considered undetermined.
A more solid approach would
probably be:



function handler() {
alert('hello'); }

$('.add_to_this').each(function() {

var link = $('Click here');

$(this).append(link);

link.click(handler);
});


No comments:

Post a Comment

php - file_get_contents shows unexpected output while reading a file

I want to output an inline jpg image as a base64 encoded string, however when I do this : $contents = file_get_contents($filename); print ...