You might want to doublecheck that when you click the elements you
took out of the loop, you really get what you say. Given your example,
if you click #page2 it should alert 'page3' also.

You don't really need the loop to attach the click and get at the
number if it's part of the id:

$('div[id^=page]').click(function(){
  console.log('page ' + this.id.replace(/page/,'') + ' clicked.');
});

Try Googling global variables, scope, and closures in JavaScript.


On May 16, 2:16 pm, mikfig <mikfi...@gmail.com> wrote:
> I have a webpage that searches a database using a php script to search
> the database and a jQuery app on the page to retrieve the results and
> show them. So it works fine, but then I want to add page number
> buttons to allow the user to go to different "pages" of the results.
> So I have a DIV with the id of "page_buttons" and I use the following
> code:http://pastebin.com/m3dffbf99
>
> I use the offset and the results per page like this in a MySQL query
> in the php script: SELECT .... LIMIT offset,
> resultsPerPage by the way.
>
> So anyways, the problem I am having is that if I have a loop like
> this:
>
> var pageNum = 6;
> ...
> for(var i = 0; i <= pageNum; ++i)
> {
>     $("#page" + i).click(function() { alert('page ' + i + '
> clicked.'); });
>
> }
>
> The elements with IDs of "page1", "page2",... are buttons, and I
> tested the above loop. What happens is if I click any of the buttons
> with IDs of "page1", "page2",.. then they all "alert" with the string
> "page 7 clicked". All the page buttons 1-6 display the string "page 7
> clicked".
>
> To try to greater understand this problem I took the functionality out
> of the loop like this:
>
> var i = 2;
> $("#page" + i).click(function() { alert('page ' + i + '
> clicked.'); });
> i = 3;
> $("#page" + i).click(function() { alert('page ' + i + '
> clicked.'); });
>
> and it worked just fine with "page2" alerting "page 2 clicked and
> "page3" alerting with "page 3 clicked".
>
> So I was hoping someone could help me in explaining why this issue
> occurs and if there was a better way to do what I'm trying to do.
>
> Thanks,
> mikfig

Reply via email to