Проблемы с текущими номерами вкладок и страниц в php - PullRequest
2 голосов
/ 24 мая 2011

там я создал программу с кнопкой вкладки и номером страницы.все функции почти работают должным образом, пока я не заметил одну крошечную проблему.как мы все знаем, вкладки всегда подсвечивают текущую вкладку, в которой вы находитесь. Допустим, если ваши вкладки состоят из букв AZ и #, что означает домашнюю или главную страницу, а # является текущей страницей, а главные страницы состоят из спискасотрудники, зарегистрированные в вашей базе данных.так как у меня есть номер страницы («Следующая» и «Предыдущая»), я ограничил количество или количество имен / информации о сотрудниках 5, указав, что на экране должно отображаться только 5 записей.

примечание: мой код работает, но1 проблема поскользнулась.каждый раз, когда я нажимал на следующую кнопку, чтобы увидеть другой список сотрудников, вкладка # не подсвечивается, и предполагается, что она по-прежнему подсвечивается, поскольку вы находитесь на той же странице.Кто-нибудь знает, с чем это связано и как это исправить?извините, если это не так ясно, потому что это так трудно объяснить.

пример: (представьте это как окно) допустим, что предел равен = 2

**#** A B C D E F G H I J K L M N O P Q R S T U V W X Y Z  //this is the tabs button, notice the # is highlighted
employee_id : employee_name : employee_age
     1          chel                26
     2         brandon              35
**PREV**                                 **NEXT**     //this is the page number

, когда япопробуйте щелкнуть рядом, чтобы просмотреть следующего сотрудника на главной странице, страница выглядит следующим образом:

# A B C D E F G H I J K L M N O P Q R S T U V W X Y Z //notice the # is NOT highlighted after you click next
employee_id : employee_name : employee_age
     3          charlie            28
     4           sasha             24
**PREV**                                 **NEXT**

Надеюсь, я решил эту проблему на этой простой иллюстрации.Я надеюсь, что кто-то может мне помочь.спасибо

//this is my tabs codes
<?php
                function toc_menu($current){
                    $return ='<ol id="toc">
                    '."\n";
                    $return .= ($current=='') ? '<li class="current"><a href="index.php?namelist=%"><span>#</span></a></li>'."\n" : '<li><a href="index.php"><span>#</span></a></li>'."\n";
                    foreach(range('a','z') as $link){
                    $return .= ($current==$link) ? '<li class="current"><a href="index.php?namelist='.$link.'"><span>'.strtoupper($link).'</span></a></li>'."\n" : '<li><a href="index.php?namelist='.$link.'"><span>'.strtoupper($link).'</span></a></li>'."\n";
                    }
                    $return .="</ol>\n";
                    return $return;
                }
            if(isset($_GET['namelist']))
            {
            $current=$_GET['namelist'];
            }
            else
            {$current='';
            }

            //echo where you want the menu
            if(isset($_GET['namelist'])) {
                echo toc_menu(strtolower($_GET['namelist']));
                $tocmenu = toc_menu(strtolower($_GET['namelist']));
            } else {
                echo toc_menu(strtolower(''));
            }
            //or hold it in a variable to display later on

                ?>
//and this is my page_number codes:
<?php if ($offset>=1) 
    { // bypass PREV link if offset is 0
        $prevoffset=$offset-$limit;
        print "<a href=\"".htmlentities($_SERVER['PHP_SELF'])."?offset=$prevoffset&searchfile=$search&namelist=$listname\"/>Prev</a> &nbsp;";
    }
    echo '</td>
            <td colspan ="5" height ="20" align="right"';
    // check to see if last page
    if (!($offset+$limit > $total))
    {
            // not last page so give NEXT link
            if ($offset == 1) 
            {
                $newoffset=$offset+($limit-1);
            } 
            else 
            {
                $newoffset=$offset+$limit;
            }
            print "<a href=\"".htmlentities($_SERVER['PHP_SELF'])."?offset=$newoffset&searchfile=$search&namelist=$listname\">Next</a> &nbsp;";
    }   
    ?>

ОБРАТИТЕ ВНИМАНИЕ: Моя переменная namelist используется для переменной AZ, файл поиска предназначен длякнопка моего поиска MisaChan

1 Ответ

0 голосов
/ 24 мая 2011

После борьбы с этим длинным фрагментом кода единственное, что я вижу, что может вызвать проблему, это $listname

, если listname не является буквой, ваш код не будет работать.

вот что я предложил, так как ваш код не отсортирован в алфавитном порядке, вы должны рассмотреть вместо использования чисел.AZ будет от 1 до 10 или 1 to total pages, это имеет гораздо больше смысла,

, вот класс, который я использую для удобной нумерации страниц

    class Pagination {

            public $current_page;
            public $per_page;
            public $page_count;

            public function __construct($page=1,$per_page= 15, $total_count=0) {
                    $this->current_page = $page;
                    $this->per_page = $per_page;
                    $this->total_count = $total_count;
            }

            public function offset() {
                    return ($this->current_page -1)* $this->per_page;
            }

            public function total_pages () {
                    return ceil($this->total_count/ $this->per_page);
            }

            public function previous_page () {
                    return $this->current_page -1;
            }

            public function next_page () {
                    return $this->current_page +1;
            }

            public function has_previous_page () {
                    return $this->previous_page() >= 1? true : false;
            }

            public function has_next_page () {
                    return $this->next_page() <= $this->total_pages()? true : false;
            }

// edit this section to suit your needs
            public function format_output ($link,$query) {
                    if ($this->total_pages() > 1) {
                            $output = "<div id=\"pagination\"><p>";
                            $output .= ($this->has_previous_page())? ("<a href=\"/$link/".$this->previous_page()."/{$query}\" >Previous</a>"): "";
                            $c = $this->current_page;
                            $t = $this->total_pages();
                            for ( $i = 1; $i <= $t; $i++ )
                            {
                                    if ($this->current_page == $i) {
                                            $output .= " <a class=\"active\" href=\"#\" >{$i}</a> ";
                                    }else {
                                            $output .= " <a href=\"/$link/{$i}/{$query}\" >{$i}</a> ";
                                            //$output .= " <a href=\"$link?q={$query}&page={$i}\" >{$i}</a> ";
                                    }
                            }
                            $output .= (($t ==$this->total_pages())?"":' ... ');
                            $output .= ($this->has_next_page())? ("<a href=\"/$link/".$this->next_page()."/{$query}\" >Next</a>"): "";
                            $output .= "</p></div>";

                    }else {
                            $output = "<div id=\"pagination\"><p>Displaying all results.</p></div>";
                    }
                    return $output;
            }
    }

    ?>

и вот как я его использую

// your listname in numbers
$currentPage = isset($_GET['currentPage'])? $_GET['currentPage']: 1; // page number 
$limit =2; // you decided to limit 2 per page
$total = 10; // the total result available in all pages

$pagination = new Pagination($currentPage, $limit,$total);

// if you need the the value of how many to offset for the current page
$offset = $pagination->offset(); // example page 6 will return 12

// and to display the pagination simply echo this
echo $pagination->format_output(htmlentities($_SERVER['PHP_SELF']),'other values u want to pass');

Это автоматически создаст для вас предыдущую и следующую кнопку

Надеюсь, это поможет вам решить вашу проблему

...