JQuery -循环通过一个数组UI对话框方法

JS - looping through an array with JQuery UI dialog method

本文关键字:一个 数组 UI 方法 对话框 循环 JQuery      更新时间:2023-09-26

我有以下jQuery代码使用jQuery UI

编辑:

$(document).ready(function(){
$('#the-link-2').click(function(){
var array = ["test1","test2","test3","test4"]
var i = 1;
while (i<array.length) {
var newDiv = $(document.createElement('div'));
  $(newDiv).html(array[i]).dialog({
buttons: {
'Previous': function() {
    $(this).dialog("close");
    i--;
    },
'Next': function() {
    $(this).dialog("close");
    i++;
    }
}
}
});
});
});

我试图循环遍历数组的项(从item# 1开始)。对话框显示项目,并根据用户单击的按钮移动到上一个/下一个项目。它不起作用(没有任何东西被解雇)。如果我删除"while"循环,我确实得到了包含#1项的对话框。谁能给我正确的语法,以获得所需的结果,请?谢谢。

我为此创建了一个小提琴并更新了您的脚本。与其循环它们,不如创建一个你想要的递归函数:

脚本

:

var array = ["test1", "test2", "test3", "test4"];
$('#the-link-2').click(function() {
    var current = 0; // current data to show
    createDialog(array[current], current); // create the dialog for current data
});
function createDialog(data, current) {
    var $div = $('<div>'); // create a new div element
    // add the html content of new div by passing array[current]
    // and create the corresponding dialog
    $div.html(data).dialog({
        buttons: {
            'Previous': function() {
                if (current == 0) {
                    // do nothing if no more prev data
                    // or you can add some extra function here
                    // like close the dialog if no more prev data
                    return; 
                } else {
                    current--;
                }
                $(this).dialog("close").remove(); // close the dialog and remove the div
                createDialog(array[current], current); // call createDialog again passing new current data
            },
            'Next': function() {
                if (current == (array.length - 1)) {
                    // do nothing if no more next data
                    // or you can add some extra function here
                    // like close the dialog if no more next data
                    return;
                } else {
                    current++; // increment current to next data
                }
                $(this).dialog("close").remove(); // close the dialog and remove the div
                createDialog(array[current], current); // call createDialog again passing new current data
            }
        }
    });
}

FIDDLE: HERE