Reputation: 55
I'm having problems adding a click event to a dynamically populated listview using JQM and Phonegap (A static list works correctly). The listview populates and applies css correctly but when I try to add a click event using the $("#test li".on("click")
the id is not selected and no code executes. Any ideas?
JS :
document.addEventListener("deviceready", onDeviceReady, false);
function onDeviceReady() {
window.requestFileSystem(LocalFileSystem.PERSISTENT, 0, onFileSystemSuccess, fail);
}
function onFileSystemSuccess(fileSystem) {
fileSystem.root.getDirectory("external_sd/Music", {
create: false,
exclusive: false
}, getDirSuccess, fail);
}
function getDirSuccess(dirEntry) {
// Get a directory reader
var directoryReader = dirEntry.createReader();
// Get a list of all the entries in the directory
directoryReader.readEntries(readerSuccess, fail);
}
function readerSuccess(entries) {
for (i = 0; i < entries.length; i++) {
$("#test").append("<li>" + entries[i].name + "</li>");
$("#test").listview("refresh");
}
}
$("#test ul li").on("click", function (event) {
alert($(this).text());
}); //this code doesn't execute.
function fail(evt) {
console.log(evt.target.error.code);
alert("some error occured");
}
HTML
<div data-role="page" id="albumspage">
<div data-role="header" data-position="fixed">
<h1>MyApp</h1>
</div><!-- /header -->
<div data-role="content">
<ul id="test" data-role="listview" data-autodividers="true">
</ul>
</div>
<div data-role="footer" data-position="fixed">
<h1>footer</h1>
</div><!-- /footer -->
</div><!-- /page -->
Upvotes: 2
Views: 11470
Reputation: 11371
Some mistakes in your code :
pageinit
event of albumspage
to render the listview, not using the deviceReady
event. refresh
ONLY once, after everything is done appending.li
inside $("#test")
. But when you're selecting the element for click event, you are using $("#test ul li")
. That can mean two things : either the way append
ing is done is wrong or your selector for click
function is wrong. From the HTML its clear that you have the wrong selector in click
. So finally your code must look like this :
function readerSuccess(entries) {
var li = "";
for (i = 0; i < entries.length; i++) {
li += "<li>" + entries[i].name + "</li>";
}
$("#test").append(li).promise().done(function () {
//refresh list here
$(this).listview("refresh");
//then add click event using delegation
$(this).on("click", "li", function () {
alert($(this).text());
});
});
}
$(document).on("pageinit", "#albumspage", function () {
//get entries from DB
readerSuccess(entries);
});
But if still want to use onDeviceReady
event, then you might want to change your click
event to this :
$(document).on("click", "#test li" ,function (event) {
alert($(this).text());
});
This binding to document
will ensure that the click will always fire.
Upvotes: 7
Reputation: 1455
Try this code
$("#test").on('click', 'li', function (e) {
var control = $(this);
}
Upvotes: 1