Note that there are some explanatory texts on larger screens.

plurals
  1. PO
    primarykey
    data
    text
    <p>So it sounds like each element should have its own <code>page</code> variable.</p> <p>An easy solution is to use <code>.each()</code> to assign the handlers, and create the <code>page</code> variable inside the <code>each</code> callback.</p> <pre><code>$('.loadMore').each(function() { var page = 1; $(this).click(function() { page++; var subcategoryId = $(this).parent().attr('data-subcategoryId'); var url = 'http://www.domain.com/request.php?subcategoryId='+subcategoryId+'&amp;page='+page; console.log(url); }); }); </code></pre> <p>Because JavaScript functions are closures, each <code>.click</code> handler has been created in its own fresh variable environment, and each handler will always have reference to the variables that were in scope at the time of creation.</p> <p>This means that each handler has its own personal <code>page</code> variable to increment.</p> <p>Another solution would be to use "event data". You can associate data with a particular element via the <code>event</code> object.</p> <pre><code>$('.loadMore').each(function() { $(this).bind("click", {page:1}, loadMoreHandler); }); function loadMoreHandler(e) { e.data.page++; var subcategoryId = $(this).parent().attr('data-subcategoryId'); var url = 'http://www.domain.com/request.php?subcategoryId='+subcategoryId+'&amp;page='+e.data.page; console.log(url); } </code></pre> <p>Since a closure is no longer taken advantage of, I used a named function for the handler for the sake of function object reuse. You can change it back to an anonymous function if it doesn't matter to you.</p>
    singulars
    1. This table or related slice is empty.
    plurals
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. VO
      singulars
      1. This table or related slice is empty.
    2. VO
      singulars
      1. This table or related slice is empty.
    3. VO
      singulars
      1. This table or related slice is empty.
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload