2

我在使用 JQM 和 Phonegap 将点击事件添加到动态填充的列表视图时遇到问题(静态列表正常工作)。列表视图正确填充并应用 css,但是当我尝试使用$("#test li".on("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");
    }

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 -->
4

2 回答 2

7

正确的方法

您的代码中的一些错误:

  • 您必须使用pageinit事件albumspage来呈现列表视图,而不是使用deviceReady事件。
  • refresh在完成所有附加操作后,您必须只使用一次。
  • 你正在附加你的liinside $("#test")。但是当您为点击事件选择元素时,您使用的是$("#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);
});

选择

但是如果仍然想使用onDeviceReady事件,那么您可能希望将您的click事件更改为:

$(document).on("click", "#test li" ,function (event) {
    alert($(this).text());
}); 

此绑定document将确保单击将始终触发。

于 2013-07-27T08:43:58.903 回答
1

试试这个代码

$("#test").on('click', 'li', function (e) {
 var control = $(this);
}
于 2013-07-27T08:46:20.867 回答