簡體   English   中英

如何使用循環使每個頁面都有滑動方法?

[英]How to make every page have swipe method by using loop?

我是新手。 我試着讓每個頁面都有一個jQuery移動網站的滑動方法,如下所示:

$("#page1").swipeleft(function () {
    $.mobile.changePage("#page2", {
        transition: "slide"
    });
});
$("#page2").swipeleft(function () {
    $.mobile.changePage("#page3", {
        transition: "slide"
    });
});

當我嘗試制作這樣的循環時,它不起作用。

var i = 1;
if(i <= 3;) {
    $("#page" + i).swipeleft(function () {
        $.mobile.changePage("#page" + (i + 1), {
            transition: "slide"
        });
    });
};

我的代碼缺少什么?

更新:嘗試此代碼,但似乎不起作用

for (var i = 1; i<=3; i++) {
    $("#page"+i).swipeleft(function () {
        $.mobile.changePage("#page"+(i+1), {
            transition: "slide"
        });
    });
}

這是我的代碼: http//jsfiddle.net/lansinz/FHnp6/1/

您實際上似乎沒有在代碼中循環。 請嘗試以下方法

//Create a loop for pages 1 to 3
for (var i = 1; i <= 3; i++) {
    //When page is 'swiped' call the nextPage() function
    $('#page' + i).on('swipeleft', nextPage);
}

function nextPage(event) {
    //Get the ID attribute of the element swiped
    var id = $(event.target).attr('id');
    //Get the number at the end of the elements ID (to work out the page number)
    var pageNo = parseInt(id.substr(4), 10);
    //Call the changePage function, increasing the page number by one
    $.mobile.changePage($('#page' + (pageNo + 1)), {
        transition: 'slide'
    });
}

jsFiddle鏈接

試試這個簡單的方法... $(document).on(“swipeleft”,'#'+ event.target.id,function(){var nextpage = $(this).next('div [data-role =“ page“]'); if(nextpage.length> 0){alert(nextpage.attr('id')); $ .mobile.changePage(nextpage,”slide“,false,true);}});

                $(document).on("swiperight", '#'+event.target.id, function () {
                    var prevpage = $(this).prev('div[data-role="page"]');
                    if (prevpage.length > 0) {
                        $.mobile.changePage(prevpage, { transition: "slide", reverse: true }, true, true);
                    }
                });

或舊學校的方式與冗長的代碼:)

$(document).on('pageshow', '#page1', function(){
    $( "#page1" ).on( 'swipeleft', function(){
        $.mobile.changePage('#page2');
    });
});

$(document).on('pageshow', '#page2', function(){
    $( "#page2" ).on( 'swipeleft', function(){
        $.mobile.changePage('#page3');
    });

    $( "#page2" ).on( 'swiperight', function(){
        $.mobile.changePage('#page1');
    });
});

$(document).on('pageshow', '#page3', function(){
    $( "#page3" ).on( 'swiperight', function(){
        $.mobile.changePage('#page2');
    });
});

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM