通过在javascript中从用户获取值来加载数据子集的问题

时间:2013-09-19 11:14:31

标签: javascript jquery

我的分页方式有问题。假设我有10页,当用户点击页码时,它会正确加载数据但我在点击下一页和上一页时遇到问题。

我有这个html文件:

 <% for(var i = 0; i < 10 ; i++){ %>
            <% if(i === 0){ %>
                <li><a class="a-page-item current" >Previous</a></li>
                <li class="a-page-item current" ><%= i+1 %></a></li>
            <% } else if(i > 0 && i < 10 - 1){ %>
                <li><a class="a-page-item current"> <%= i+1%> </a></li>
            <% } %>
        <% } %>

    <li class="arrow"><a class="a-page-item current" >Next</a></li>

我的问题是,当我点击下一步时,我想要将当前页面添加为1.但我不知道如何处理“Next”这是一个字符串。我需要将当前页面保留在某处,然后当我单击“下一步”时,它会将当前页面添加1。多数民众赞成我尝试过,但我收到错误,因为它想加载“下一步”,这是字符串而不是当前页+1!

onPageClick : function(event) {

                var currentPage = event.target.innerHTML;
                if (currentPage == "Next"){

                    var currentPageInt = parseInt(currentPage);
                    this.currentPageInt +1;
                    this.setPagination(currentPageInt, 10);
                }


                else if (currentPage == "previous"){

                    var currentPageInt = parseInt(currentPage);
                    this.currentPageInt - 1;
                    this.setPagination(currentPageInt, 10);

                }

                else {
                var currentPageInt = parseInt(currentPage);
                this.setPagination(currentPageInt, 10);

            }

            },

this. setPagination(currentPageInt, 10);从用户选择的页面加载10个数据。

2 个答案:

答案 0 :(得分:0)

这是怎么回事?

onPageClick : function(event) {
  var currentPage = event.target.innerHTML;
  if (currentPage === "Next") {
    this.currentPageInt++;
  } else if (currentPage === "Previous") {
    this.currentPageInt--;
  } else {
    this.currentPageInt = parseInt(currentPage);
  }
  this.setPagination(this.currentPageInt, 10);
},

答案 1 :(得分:0)

也许您已经注意到了这一点,但是您正在尝试解析“下一个”和“上一个”,这会导致NaN(非数字):

if currentPage == 'Next'
    parseInt('Next') // NaN
if currentPage == 'previous'
    parseInt('previous') // NaN

另外要注意“previous”,实际的内部HTML是“Previous”:

"previous" == "Previous" // false

为防止此类错误稍后重复,您可以使用class属性。这将允许您更改内部HTML而无需更新javascript部分:

<a class="next">Next page</a>
<a class="previous">Previous page</a>
if jQuery(e.target).hasClass('next')
    // increment
if jQuery(e.target).hasClass('previous')
    // decrement

另一点是您目前不保存增量值:

this.currentPageInt = 1;
this.currentPageInt + 1; // 2
this.currentPageInt; // still 1

以下是解决此问题的各种方法(-相同):

this.currentPageInt = this.currentPageInt + 1;
this.currentPageInt; // 2
this.currentPageInt += 1;
this.currentPageInt; // 3
this.currentPageInt++;
this.currentPageInt; // 4

那就是var currentPageInt没用,你应该完全删除它并使用this.currentPageInt代替。但更重要的是,仅在第三种情况下解析(当用户点击页码时)可以解决您的问题。