2013-10-21 50 views
0

這是我的代碼..當我調用這個函數時,iScroll()在更改頁面後的LI元素上添加了重複事件。在iScroll的LI元素上重複onClick事件

function collectionOffen(asseID, imgsInFile) { 
    $("#thelist").empty(); 

    // append image files into slider div.. 
    for (var imgPageCnt = 0; imgPageCnt <= imgsInFile; imgPageCnt++) { 
     var html = ""; 
     html += "<li id=" + imgPageCnt + ">"; 
     html += "<img src='" + preThmb + "'>"; 
     html += "</li>"; 

     $("#thelist").append(html); 

     funcPreImg = function() { 
      previewImageBackside(asseID); 
     } 

     document.getElementById(imgPageCnt).addEventListener("click", funcPreImg); 
    } 

    $("#thelist").listview("refresh"); 
    $.mobile.changePage("#collectionOfFiles", { 
     transition: "slide", 
     reverse: true 
    }); 
    var myScroll = new iScroll('wrapper'); 
} 

告訴我解決辦法,如果任何..

+0

建議您以字母開頭,而不是數字開頭。 – Omar

回答

1

重複的事件是JQM一個共同的問題。

試試這個(untestet braincode):

$(document).on('pageinit', function() { 
    $("#thelist").empty(); 

    // append image files into slider div.. 
    for (var imgPageCnt = 0; imgPageCnt <= imgsInFile; imgPageCnt++) { 
     var html = ""; 
     html += "<li id='" + imgPageCnt + "' class='imgClass'>"; 
     html += "<img src='" + preThmb + "'>"; 
     html += "</li>"; 

     $("#thelist").append(html); 
    } 

    //is 'asseID' defined in this context? 
    $(document).on('click', '.imgClass', function (e) { 
     if(e.handled !== true) 
     { 
      previewImageBackside(asseID); 
      e.handled = true; 
     } 
    }); 

    $("#thelist").listview("refresh"); 
    $.mobile.changePage("#collectionOfFiles", { 
     transition: "slide", 
     reverse: true 
    }); 
    var myScroll = new iScroll('wrapper'); 
}); 

這應該只在頁面初始化添加列表元素。

也改變了你的JavaScript函數到一個更好的和高性能的jquerycall。

你也有一個錯字在"<li id='" + imgPageCnt + "'>",缺失報價

+0

當你評論iScroll(),然後代碼工作正常。 iScroll添加了重複事件。 – Saurabh

+0

更新了我的示例,如果事件被處理,它將不會執行兩次 – tronc

+0

您的解決方案不工作Tronc。 – Saurabh

0

我找到了解決方案。渲染圖像後銷燬iScroll對象。

例如: -
var myScroll = new iScroll('wrapper'); myScroll.refresh(); myScroll.destroy();

將myScroll作爲靜態變量來銷燬對象。