简体   繁体   中英

Show first and last page only when there is more than one page number using jquery or javascript?

I have two buttons like this:

 <button class="next_prev" onclick="" id="first_buttons" disabled>{{ pages.first }}</button>
<button class="next_prev" onclick="" id="last_buttons" disabled>{{ pages.last }}</button>

If there is only one page by default the page {{ pages.first }} and {{ pages.last }} store the page number 1 and 1 and show it. But I only want to show these two buttons if page number is great than 1. I get page length like this:

<p> <span>{% get_pages %} {{ pages|length }} pages</span> </p>

Can it be done in jquery or javascript? Thanks

How about adding a common class to each button, eg:

<button class="next_prev pageNumberBtn" onclick="" id="first_buttons" disabled>{{ pages.first }}</button>

<button class="next_prev pageNumberBtn" onclick="" id="last_buttons" disabled>{{ pages.last }}</button>

Then hide the buttons if the last page number is 1:

if ($('#last_buttons').html() == '1') {
    $('.pageNumberBtn').hide();
}

Give the wrapper of the page length number with a class/ID. For example:

<p id="num-of-pages"><span>{% get_pages %} {{ pages|length }} pages</span></p>

If the output of the above code only churns out some numbers only, you can use this jQuery code below to hide the buttons:

var numOfPages = $('#num-of-pages').text();

if (numOfPages <= 1 ){
    $('.next_prev').hide();
}

Example fiddle here: http://jsfiddle.net/shodaburp/56kbj/

PS: Just a tip - since .next_prev is quite a generic name and you might have used this class for some other elements, better to give some IDs to those two buttons that you want to hide.

UPDATE (Based on user2032220's second comment):

If {% get_pages %} {{ pages|length }} actually output "Pages 1" then one of the easiest solution is to wrap the page length in another span tag. For example:

<p id="num-of-pages"><span>{% get_pages %} <span>{{ pages|length }}</span></span></p>

Then the code to hide the buttons would be to change:

var numOfPages = $('#num-of-pages span span').text();

Example fiddle: http://jsfiddle.net/shodaburp/56kbj/1/

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM