开发者

jquery, is it possible to store information in a variable, rather than an input field?

I want to store the current page number in a jquery variable, but I am not sure if it is possible, so I am storing it in an input field. Am I doing it the most efficient way?

<input type='hidden' id='current_page' /> 

$('#current_page').val(0);  

if page is changed,

function (newpage){
$('#c开发者_高级运维urrent_page').val(page_num);
}


You can use jQuery.data() for this -as mentioned by Nikita.

But if you'd like to support the JavaScript-disabled clients as well, then I'd stick to a hidden input element. This way you can still control the pagination from the server side on. The hidden input value can then be used to inform the server side what page the client is currently sitting in.


With JQuery you can store data in any DOM element, input or not

$('#current_page').data('page', 0); // save value
$('#current_page').data('page'); // return value

http://api.jquery.com/data/

As I said, you don't have to add special html element for that, any one existing will work.


The other 2 answers are correct, and you can also store it in a javascript variable if you want. Just use a closure. Something like this (but I'm not running this code ... it's conceptual only).

$(document).ready(function() {
   var pageNumber = 0;

   // This func can access "pageNumber" even
   //  though the var was declared in outer
   //  scope.
   function goToNewPage(newPageNumber) {
      pageNumber = newPageNumber;
   }

   // This func can access "pageNumber" even
   //  though the var was declared in outer
   //  scope.
   function getCurrentPageNumber() {
      return pageNumber;
   }

}
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜