【问题标题】:Disable the first previous button on dynamic page numbers禁用动态页码上的第一个上一个按钮
【发布时间】:2017-09-07 18:28:04
【问题描述】:

我有一个弹出窗口来显示用户列表,每页显示 10 个结果,效果很好。

我正在获取页码。来自 JSON 中的 java servlet。 当它是第一页时,如何禁用上一个按钮? 同样,当最后一页是最后一页时,如何禁用最后一个按钮?

这是我的代码。

function userList(pageNo) {

	var resType="userList";
				
	createTable(resType,pageNo);
	$(document).on('click', '.next-btn', function(){
		var next = 10+pageNo;
		userList(next);

	});
	$(document).on('click', '.prev-btn', function(){
		var previ = pageNo - 10;
		userList(previ);
	});
}

function createTable(resType, pageNo) {
    $.getJSON("https://api.randomuser.me/?results="+pageNo, function(data) {
        $('#datatable tr:has(td)').remove();
        data.results.forEach(function (record) {
            var json = JSON.stringify(record);
            $('#datatable').append(
                $('<tr>').append(
                    $('<td>').append(
                        $('<input>').attr('type', 'checkbox')
                                    .addClass('selectRow')
                                    .val(json)
                    ),
                    $('<td>').append(
                        $('<a>').attr('href', record.picture.thumbnail)
                                .addClass('imgurl')
                                .attr('target', '_blank')
                                .text(record.name.first)
                    ),
                    $('<td>').append(record.dob)
                )
            );
        })
    }).fail(function(error) {
        console.log("**********AJAX ERROR: " + error);
    });            
}

var savedData = []; // The objects as array, so to have an order.

function saveData(){
    var errors = [];
    // Add selected to map
    $('input.selectRow:checked').each(function(count) {
        // Get the JSON that is stored as value for the checkbox
        var obj = JSON.parse($(this).val());
        // See if this URL was already collected (that's easy with Set)
        if (savedData.find(record => record.picture.thumbnail === obj.picture.thumbnail)) {
            errors.push(obj.name.first);
        } else {
            // Append it
            savedData.push(obj);
        }
    });
    refreshDisplay();
    if (errors.length) {
        alert('The following were already selected:\n' + errors.join('\n'));
    }
}

function refreshDisplay() {
    $('.container').html('');
    savedData.forEach(function (obj) {
        // Reset container, and append collected data (use jQuery for appending)
        $('.container').append(
            $('<div>').addClass('parent').append(
                $('<label>').addClass('dataLabel').text('Name: '),
                obj.name.first + ' ' + obj.name.last,
                $('<br>'), // line-break between name & pic
                $('<img>').addClass('myLink').attr('src', obj.picture.thumbnail), $('<br>'),
                $('<label>').addClass('dataLabel').text('Date of birth: '),
                obj.dob, $('<br>'),
                $('<label>').addClass('dataLabel').text('Address: '), $('<br>'),
                obj.location.street, $('<br>'),
                obj.location.city + ' ' + obj.location.postcode, $('<br>'),
                obj.location.state, $('<br>'),
                $('<button>').addClass('removeMe').text('Delete'),
                $('<button>').addClass('top-btn').text('Swap with top'),
                $('<button>').addClass('down-btn').text('Swap with down')
            )	
        );
    })
    // Clear checkboxes:
    $('.selectRow').prop('checked', false);
    handleEvents();
}

function logSavedData(){
    // Convert to JSON and log to console. You would instead post it
    // to some URL, or save it to localStorage.
    console.log(JSON.stringify(savedData, null, 2));
}

function getIndex(elem) {
    return $(elem).parent('.parent').index();
}

$(document).on('click', '.removeMe', function() {
    // Delete this from the saved Data
    savedData.splice(getIndex(this), 1);
    // And redisplay
    refreshDisplay();
});

/* Swapping the displayed articles in the result list */
$(document).on('click', ".down-btn", function() {
    var index = getIndex(this);
    // Swap in memory
    savedData.splice(index, 2, savedData[index+1], savedData[index]);
    // And redisplay
    refreshDisplay();
});

$(document).on('click', ".top-btn", function() {
    var index = getIndex(this);
    // Swap in memory
    savedData.splice(index-1, 2, savedData[index], savedData[index-1]);
    // And redisplay
    refreshDisplay();
});
    
/* Disable top & down buttons for the first and the last article respectively in the result list */
function handleEvents() {
    $(".top-btn, .down-btn").prop("disabled", false).show();
    $(".parent:first").find(".top-btn").prop("disabled", true).hide();
    $(".parent:last").find(".down-btn").prop("disabled", true).hide();
}

$(document).ready(function(){
    $('#showExtForm-btn').click(function(){
        $('#extUser').toggle();
    });
    $("#extUserForm").submit(function(e){
        addExtUser();
        return false;
   });
});

function addExtUser() {
    var extObj = {
        name: {
            title: "mr", // No ladies? :-)
            first: $("#name").val(),
            // Last name ?
        },
        dob: $("#dob").val(),
        picture: {
            thumbnail: $("#myImg").val()
        },
        location: { // maybe also ask for this info?
        }
    };
    savedData.push(extObj);
    refreshDisplay(); // Will show some undefined stuff (location...)
}
table, th, td {
    border: 1px solid #ddd;
    border-collapse: collapse;
    padding: 10px;
}

.parent {
    height: 25%;
    width: 90%;
    padding: 1%;
    margin-left: 1%;
    margin-top: 1%;
    border: 1px solid black;

}

.parent:nth-child(odd){
    background: skyblue;
}

.parent:nth-child(even){
    background: green;
}

label {
    float: left;
    width: 80px;
}
input {
    width: 130px;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<button onclick="userList(0)">Create Table</button>
<table id="datatable">
    <tr><th>Select</th><th>Name</th><th>DOB</th></tr>
</table>
<button onclick="saveData()">Save Selected</button>
<br />
<div class="container"></div>
<button onclick="logSavedData()">Get Saved Data</button>
<button id="showExtForm-btn">Open External Form</button>

<div id="extUser" style="display:none">
    <form id="extUserForm">
        <p>
            <label for="name">Name:</label>
            <input type="text" id="name" required>
        </p>
        <br />
        <p>
            <label for="myImg">Image:</label>
            <input type="url" id="myImg" required>
        </p>
        <br />
        <p>
            <label for="dob">DOB:</label>
            <input type="date" id="dob" required>
        </p>
        <br />
        <button>Submit</button>
    </form>
</div>

【问题讨论】:

  • 您的 URL 参数 results 不是确定页面(第一条记录),而是确定要返回的记录数。对于设置记录的第一个数字,您还有其他论据吗?
  • 你怎么知道你的最后一页是什么?你有记录数吗?来自服务器的特定响应?

标签: javascript jquery dynamic pagination


【解决方案1】:

检查previ 的值是否小于或等于10,如果这样隐藏它。相同的反向逻辑适用于下一个按钮。在下一个按钮上,您可以显示 prev-btn

$(document).on('click', '.prev-btn', function(){
        var previ = pageNo - 10;
        if(previ < = 10)
          $(this).hide();
        UserList(previ);
    });

【讨论】:

  • 谢谢,但它不起作用!它将所有结果隐藏在弹出窗口而不是按钮中。
  • 显示您的 html 。它唯一的隐藏按钮具有类 `.prev-btn`
  • 请忽略脚本中的html错误。我不能完全使用页码。因为在我的 JSON url 中它来自 JAVA servlet。因此,该页没有。不会在 url 中工作。否则,逻辑保持不变!
【解决方案2】:

您应该将上一个/下一个按钮作为隐藏添加到您的 HTML 中,然后通过 ID 而不是类来引用它们(因为您将只有一个)。

在全局变量中跟踪当前页码。

仅当页码大于 0 时才显示“上一个”按钮。对于“下一个”按钮,您可以应用此技巧:

不是加载 10 条记录,而是再加载一条,但不是为了显示:如果存在,那么“下一步”按钮应该是可见的。

这是一个带有这些更改的 sn-p(所有更改都在 HTML 和脚本的顶部):

var currentPageNo = 0; // Keep track of currently displayed page

$('#next-btn').click(function(){ // Give buttons an ID (include them in HTML as hidden)
    userList(currentPageNo+10);
});
$('#prev-btn').click(function(){
    userList(currentPageNo-10);
});

function userList(pageNo) {
	var resType="userList";
	createTable(resType,pageNo);
}

function createTable(resType, pageNo) {
    // Update global variable
    currentPageNo = pageNo; 
    // Set visibility of the "prev" button:
    $('#prev-btn').toggle(pageNo > 0);
    // Ask one record more than needed, to determine if there are more records after this page:
    $.getJSON("https://api.randomuser.me/?results=11&start="+pageNo, function(data) {
        $('#datatable tr:has(td)').remove();
        // Check if there's an extra record which we do not display, 
        // but determines that there is a next page
        $('#next-btn').toggle(data.results.length > 10);
        // Slice results, so 11th record is not included:
        data.results.slice(0, 10).forEach(function (record, i) { // add second argument for numbering records
            var json = JSON.stringify(record);
            $('#datatable').append(
                $('<tr>').append(
                    $('<td>').append(
                        $('<input>').attr('type', 'checkbox')
                                    .addClass('selectRow')
                                    .val(json),
                        (i+1+pageNo) // display row number
                    ),
                    $('<td>').append(
                        $('<a>').attr('href', record.picture.thumbnail)
                                .addClass('imgurl')
                                .attr('target', '_blank')
                                .text(record.name.first)
                    ),
                    $('<td>').append(record.dob)
                )
            );
        });
        // Show the prev and/or buttons
        
        
    }).fail(function(error) {
        console.log("**********AJAX ERROR: " + error);
    });            
}

var savedData = []; // The objects as array, so to have an order.

function saveData(){
    var errors = [];
    // Add selected to map
    $('input.selectRow:checked').each(function(count) {
        // Get the JSON that is stored as value for the checkbox
        var obj = JSON.parse($(this).val());
        // See if this URL was already collected (that's easy with Set)
        if (savedData.find(record => record.picture.thumbnail === obj.picture.thumbnail)) {
            errors.push(obj.name.first);
        } else {
            // Append it
            savedData.push(obj);
        }
    });
    refreshDisplay();
    if (errors.length) {
        alert('The following were already selected:\n' + errors.join('\n'));
    }
}

function refreshDisplay() {
    $('.container').html('');
    savedData.forEach(function (obj) {
        // Reset container, and append collected data (use jQuery for appending)
        $('.container').append(
            $('<div>').addClass('parent').append(
                $('<label>').addClass('dataLabel').text('Name: '),
                obj.name.first + ' ' + obj.name.last,
                $('<br>'), // line-break between name & pic
                $('<img>').addClass('myLink').attr('src', obj.picture.thumbnail), $('<br>'),
                $('<label>').addClass('dataLabel').text('Date of birth: '),
                obj.dob, $('<br>'),
                $('<label>').addClass('dataLabel').text('Address: '), $('<br>'),
                obj.location.street, $('<br>'),
                obj.location.city + ' ' + obj.location.postcode, $('<br>'),
                obj.location.state, $('<br>'),
                $('<button>').addClass('removeMe').text('Delete'),
                $('<button>').addClass('top-btn').text('Swap with top'),
                $('<button>').addClass('down-btn').text('Swap with down')
            )	
        );
    })
    // Clear checkboxes:
    $('.selectRow').prop('checked', false);
    handleEvents();
}

function logSavedData(){
    // Convert to JSON and log to console. You would instead post it
    // to some URL, or save it to localStorage.
    console.log(JSON.stringify(savedData, null, 2));
}

function getIndex(elem) {
    return $(elem).parent('.parent').index();
}

$(document).on('click', '.removeMe', function() {
    // Delete this from the saved Data
    savedData.splice(getIndex(this), 1);
    // And redisplay
    refreshDisplay();
});

/* Swapping the displayed articles in the result list */
$(document).on('click', ".down-btn", function() {
    var index = getIndex(this);
    // Swap in memory
    savedData.splice(index, 2, savedData[index+1], savedData[index]);
    // And redisplay
    refreshDisplay();
});

$(document).on('click', ".top-btn", function() {
    var index = getIndex(this);
    // Swap in memory
    savedData.splice(index-1, 2, savedData[index], savedData[index-1]);
    // And redisplay
    refreshDisplay();
});
    
/* Disable top & down buttons for the first and the last article respectively in the result list */
function handleEvents() {
    $(".top-btn, .down-btn").prop("disabled", false).show();
    $(".parent:first").find(".top-btn").prop("disabled", true).hide();
    $(".parent:last").find(".down-btn").prop("disabled", true).hide();
}

$(document).ready(function(){
    $('#showExtForm-btn').click(function(){
        $('#extUser').toggle();
    });
    $("#extUserForm").submit(function(e){
        addExtUser();
        return false;
   });
});

function addExtUser() {
    var extObj = {
        name: {
            title: "mr", // No ladies? :-)
            first: $("#name").val(),
            // Last name ?
        },
        dob: $("#dob").val(),
        picture: {
            thumbnail: $("#myImg").val()
        },
        location: { // maybe also ask for this info?
        }
    };
    savedData.push(extObj);
    refreshDisplay(); // Will show some undefined stuff (location...)
}
table, th, td {
    border: 1px solid #ddd;
    border-collapse: collapse;
    padding: 10px;
}

.parent {
    height: 25%;
    width: 90%;
    padding: 1%;
    margin-left: 1%;
    margin-top: 1%;
    border: 1px solid black;

}

.parent:nth-child(odd){
    background: skyblue;
}

.parent:nth-child(even){
    background: green;
}

label {
    float: left;
    width: 80px;
}
input {
    width: 130px;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<button onclick="userList(0)">Load First Page</button>
<button id="next-btn" style="display:none">Next Page</button>
<button id="prev-btn" style="display:none">Previous Page</button>
<table id="datatable">
    <tr><th>Select</th><th>Name</th><th>DOB</th></tr>
</table>
<button onclick="saveData()">Save Selected</button>
<br />
<div class="container"></div>
<button onclick="logSavedData()">Get Saved Data</button>
<button id="showExtForm-btn">Open External Form</button>

<div id="extUser" style="display:none">
    <form id="extUserForm">
        <p>
            <label for="name">Name:</label>
            <input type="text" id="name" required>
        </p>
        <br />
        <p>
            <label for="myImg">Image:</label>
            <input type="url" id="myImg" required>
        </p>
        <br />
        <p>
            <label for="dob">DOB:</label>
            <input type="date" id="dob" required>
        </p>
        <br />
        <button>Submit</button>
    </form>
</div>

由于此 URL 提供随机数据,当您重新访问页面时,这些页面将不会显示相同的数据。此外,这个随机数据集中显然没有最后一页。我已经猜到用于指定第一条记录的 URL 参数(start),因为results 参数用于指定页面大小,而不是第一条记录号。根据需要进行调整。

【讨论】:

  • 谢谢,如果我还有 1 个按钮调用相同的 createTable 函数怎么办?我在那里也使用相同的上一个和下一个按钮。它与 userList 函数非常相似。只有结果类型不同。在这种情况下,从 JSON 接收的数据是不同的,因为我也在从 JSON 中检索 resultType。但是,实现、外观和感觉 (UI) 保持完全相同。功能 myAdminList(pageNo){var resType="myadmingroup"; createTable(resType, pageNo);}
  • 是的,当然。但是您必须定义已经在内存中和div.container 部分中选择的对象需要发生什么:他们会继续保留信息吗?然后您会允许将这两种类型的混合收集到该选择中吗?您需要调整这些项目的显示方式,以及它们的键控方式(两种类型都存在缩略图 URL?),因此它们可以同时处理这两种类型......等等。我认为您需要在这方面做一些工作在回来之前;-)
  • 是的,没关系。我也需要他们在那里。我需要两者的混合,所以这部分工作正常。我实际上已经将它们用作模态。为了更好地解释它,请检查小提琴链接。唯一没有按预期工作的部分是下一个和上一个按钮,理想情况下应该分别在最后一页和第一页禁用。此外,当我单击下一个和上一个按钮时,模态表中的数据会自动刷新或更改多次! jsfiddle.net/Sunny1719/tnnyhbsn
  • 我在那个小提琴中没有看到太多的混合:它只有一个按钮来加载用户列表。
  • 抱歉,我现在添加了所有按钮。我创建这个小提琴只是为了展示它的样子。如果您需要任何信息,请告诉我。 jsfiddle.net/Sunny1719/tnnyhbsn/2
猜你喜欢
  • 2017-09-09
  • 2013-11-15
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2012-07-02
  • 2017-08-30
相关资源
最近更新 更多