sphinks
sphinks

Reputation: 3128

How to add onclick event in dynamicly add html code via JavaScript?

I try to add some list element in loop via JS. Every element <li>contains <a> tag, now I want to add onClick event in every adding <a> tag. I try to do it so:

liCode = '<li><a href="#">Text using variable foo: ' + foo + '</a></li>';
$('#list').append(function() {
    return $(liCode).on('click', clickEventOccurs(foo));
});

In clickEventOccurs I just output to console foo. It works in strange way: this event performed just on init when every tag is adding to list, but after click on <a> doesn`t perform anything. How to make it works in proper way - on click performed code in clickEventOccurs?

Upvotes: 1

Views: 2946

Answers (4)

Manu
Manu

Reputation: 819

http://jsfiddle.net/lnplnp/uGJnc/

HTML :

<ol id="list">
  <li><a href="#">Text using variable foo: foovalue</a></li>
</ol>

JAVASCRIPT/JQUERY :

function appending(foo) {
    liCode = '<li><a href="#">Text using variable foo: ' + foo + '</a></li>';
    $('#list').append($(liCode));
}

$('#list').on('click', 'li', function() {
    return clickEventOccurs($("a", this).text());
});

function clickEventOccurs(v){
    console.log(v.split(":")[1].trim());
}

appending("foo1");
appending("foo2");
appending("foo3");

Upvotes: 1

Daniel Apt
Daniel Apt

Reputation: 2648

on() is good for handling events, even to elements which will be created dynamically.

$('body').on('click', '#list li', function(){
    clickEventOccurs(foo);
});

Upvotes: 2

Jivings
Jivings

Reputation: 23260

To pass a variable to that function you'll have to make a second anonymous one, otherwise your clickEventOccurs function will be called at assignment, not as a callback.

$('#list').append(function() {
    return $(liCode).click(function() {
      clickEventOccurs(foo)
    });
});

Upvotes: 0

Igor Dymov
Igor Dymov

Reputation: 16460

Firstly, you are assigning not a callback function, but a result of function evaluation. In right way it should be like this:

$('#list').append(function() {
    return $(liCode).click(function() {
        clickEventOccurs(foo);
    });
});

Also, as you are using jQuery you might use benefits of events delegation and use .on method this way:

$('#list').on('click', 'li', function() {
    return clickEventOccurs(foo);
});

Upvotes: 4

Related Questions