and*_*013 2 jquery-mobile cordova
我在使用JQM和Phonegap(静态列表正常工作)将点击事件添加到动态填充的列表视图时遇到问题.listview正确填充和应用css,但是当我尝试使用$("#test li".on("click")id 添加click事件时,未选择id并且没有代码执行.有任何想法吗?
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");
}
Run Code Online (Sandbox Code Playgroud)
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 -->
Run Code Online (Sandbox Code Playgroud)
代码中的一些错误:
pageinit事件albumspage来呈现列表视图,而不是使用该deviceReady事件.refresh在完成所有操作后,您必须只使用一次.li内心$("#test").但是当您选择click事件的元素时,您正在使用$("#test ul li").这可能意味着两件事:要么完成的方式append是错误的,要么你的click功能选择器是错误的.从HTML中可以清楚地知道你有错误的选择器click. 所以最后你的代码必须如下所示:
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);
});
Run Code Online (Sandbox Code Playgroud)
但是如果仍然想要使用onDeviceReady事件,那么您可能希望将click事件更改为:
$(document).on("click", "#test li" ,function (event) {
alert($(this).text());
});
Run Code Online (Sandbox Code Playgroud)
这种绑定document将确保点击始终触发.
| 归档时间: |
|
| 查看次数: |
11411 次 |
| 最近记录: |