2

Faced with a problem that jquery doesn't allow to select appended element. I've seen a lot of advices how to solve it. For example:

var $li = $('<li><span>' + html + '</span></li>');
$('.top').append($li);

But it can't help me in my way. I get from server list of records from database in json format and in my view and I loop by this list and generate some html structure.

For example:

$.getJSON( "/searchbytype", data, function( data ) {
    $.each( data, function( key, val ) {
        $('items').append('<li class="item">'+ val.name + '</li>');
    });
});

And what I want to do next is click on some li item and to do some manipulation. Ul list may contain 100-200 li tags. Any ideas would be appreciated!

user3673623
  • 1,795
  • 2
  • 12
  • 18

2 Answers2

3

I think you need event-delegation

$('body').on('click', 'li', function(){
   // this handler will work even for dynamically created <li>
});
Amit Joki
  • 58,320
  • 7
  • 77
  • 95
1

You can do it like this:

$.getJSON("/searchbytype", data, function (data) {
    $.each(data, function (key, val) {
        $('<li>', {
            class: 'item'
        }).html(val.name).on('click', function () {
            // Your code here.
        }).appendTo('.items');
    });
});

Note: I'm assuming the container is an element with class equals items, so I've added a missing . to prefix it in the jQuery selector.

emerson.marini
  • 9,331
  • 2
  • 29
  • 46