Items appended to listview are not clickable

When I add content to my listview in jQuery Mobile, they don't trigger the click event when clicked. In my example below, 'Cadillac' is not clickable. Am I doing something wrong?

HTML:

<div data-role="page" id="p1">
    <ul data-role="listview" data-theme="b">
        <li><a href="#">Acura</a></li>
        <li><a href="#">Audi</a></li>
        <li><a href="#">BMW</a></li>
    </ul>
</div> 

jQuery:

$('li').on('click',function(){
    alert('clicked');            
});

$('ul').append('<li><a href="#">Cadillac</a></li>');
$('ul').listview('refresh');

jsFiddle of the issue

Answers


Try to change your code to this

$('ul').on('click', 'li', function(){   # <-- That's the trick
    alert('clicked');            
});

$('ul').append('<li><a href="#">Cadillac</a></li>');
$('ul').listview('refresh');

EDIT: In this case on function automagically binds click to every li element in list even when DOM changes. So you can add list items whenever you want. All of them will have click event binding.

Using old live jQuery method with almost same functionality is a bad idea cause of it very sloooow performance.


Need Your Help

Onclick does not work using Bootstrap

javascript jquery html django twitter-bootstrap

I have worked with Django and Bootstrap, and I have a problem with onclick attribute. When I click on a button, it does not show me nothing. Here are the HTML:

Complete Class at Cursor Not Working

delphi ide delphi-xe2 code-completion aqtime

I've been widely making use of the Complete Class at Cursor function in Delphi, in 2010 and in XE2. Recently, after installing Update 4 for XE2, the Complete Class at Cursor stopped working. After ...

About UNIX Resources Network

Original, collect and organize Developers related documents, information and materials, contains jQuery, Html, CSS, MySQL, .NET, ASP.NET, SQL, objective-c, iPhone, Ruby on Rails, C, SQL Server, Ruby, Arrays, Regex, ASP.NET MVC, WPF, XML, Ajax, DataBase, and so on.