禁用动态页码上的第一个上一个按钮 [英] Disable the first previous button on dynamic page numbers

查看:118
本文介绍了禁用动态页码上的第一个上一个按钮的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个弹出窗口显示用户列表,每页显示10个结果,这是正常的。

I've a pop-up to display the user list which would display 10 results per page, which is working fine.

我正在获得页面。从JSON中的java servlet。
如何禁用上一个按钮,当它是第一页?
同样,如果最后一个按钮是最后一个按钮,那么如何禁用最后一个按钮?

I'm getting the page nos. from the java servlet in the JSON. How do I disable the previous button, when it is the first page? Likewise, how do I disable the last button, when it is the last page?

这是我的代码。

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>

推荐答案

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

You should add the prev/next buttons to your HTML as hidden, and then reference them by ID instead of class (as you will only have one of each).

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

Keep track of the current page number in a global variable.

仅当页码大于0时显示prev按钮。 下一个按钮可以应用这个技巧:

Show the "prev" button only when the page number is greater than 0. For the "next" button you could apply this trick:

代替加载10条记录,加载一个,但不显示:如果存在,那么下一个按钮应该是可见的。

Instead of loading 10 records, load one more, but not for display: if it exists, then the "next" button should be visible.

这是一个带有这些更改的代码段(所有更改都在HTML和脚本的顶部):

Here is a snippet with those changes (all changes are in HTML and top part of the script):

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参数(开始),因为结果参数是用于指定页面大小,不是第一个记录号。根据需要进行调整。

As this URL provides random data, the pages will not show the same data when you revisit them. Also, there is apparently no last page in this random data set. I have guessed the URL parameter for specifying the first record (start), since the results parameter is for specifying the page size, not the first record number. Adapt as needed.

这篇关于禁用动态页码上的第一个上一个按钮的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆