YII2-你所该知道的杀马特操作-快速跳转至某页

博客 · 本文由 · 加班中途去撩妹 · 发布于 1年前 · 1195 阅读

有以下需求输入页数按回车跳转至某一页,效果如下

思路如下,获取到当前的url,并且获取到总页数

View:

<?php
$view = '';
$pageCount=$dataProvider->pagination->pageCount;
if ( $pageCount> 1) {
    $url = $dataProvider->pagination->createUrl(0);
    $view = '<input id="input-gopage" style="display: inline;float: left;margin-top: 5px;width: 100px" type="number" class="btn btn-default" placeholder="共'.$pageCount.'页" data-url="' . $url . '">';
}
?>
<?= GridView::widget([
    'dataProvider' => $dataProvider,
    'id' => 'stock-control',
    'columns' => $columns,
    'formatter' => ['class' => 'yii\i18n\Formatter', 'nullDisplay' => ''],
    'emptyText' => '当前没有找到库存记录',
    'emptyTextOptions' => ['style' => 'min-height: 360px;color:red;font-weight:bold'],
    'layout' => "<div style=\"margin:auto 2px;\" class=\"row\" id=\"stock-control-grid-view\">{items}</div>\n<div>{pager}" . $view . "</div>{summary}",
    'showOnEmpty' => true,
    'options' => ['class' => 'storehouse-stock-grid-view '],
    'rowOptions' => ['class' => 'item-focus-base tr-item']
]) ?>

Controller:

$dataProvider = new ActiveDataProvider([
    'query' => $model->getQuery()->orderBy([
        'id' => SORT_ASC,]),
    'pagination' => [
        'pageSize' => 20,
        'totalCount'=>$model->getQuery()->count(),
    ],
    'key' => StockControlBean::COLUMN_NAME_sku,
    'sort' => ['defaultOrder' => [StorehouseStockAR::COLUMN_NAME_id => SORT_DESC]],

]);

JS:

$('input#input-gopage').keyup(function (event) {
        if(event.keyCode==13){
            var url=$(this).attr('data-url');
            var url2=url.replace('page=1','page='+$(this).val());
            window.location.replace(url2);
        }
    });

Controller 对 ActiveDataProvider 设置 totalCount 总数目属性,View$pageCount=$dataProvider->pagination->pageCount;获取到总页数, $url = $dataProvider->pagination->createUrl(0);,构建page1 的url并且携带在input的data-url中,部分则需要监测输入回车,并且获取到urlpage=1属性替换成'page='+输入的值即可, window.location.replace(url2) 实现页面跳转

评论数量:0