for (i = 1; i < 5; i++) {
    $('#thumb' + i).bind('mouseover',function(event) {
       $(this).addClass('dim');
    });
  }

The 'i' you've called here is a global variable, in a for loop always
put a var in front of it to have local scope (to the function, not
block)

  for (var i = 1; i < 5; i++) {
    $('#thumb' + i).bind('mouseover',function(event) {
       $(this).addClass('dim');
    });
  }

but... more importantly, reframe your thoughts on javascript/jquery
programming to let the selectors do the iteration for you.

$('img[class="thumb"]).mouseover(function () {
     $(this).addClass('dim');
});


To your second question:

var elem<%=i%> = 'foo';

works because jsp is compiled server side and outputs the value of i
onto the page, so that if i is 1, then what the browser sees is

var elem1 = 'foo';

which is valid javascript.  But javascript is all done client side so

var elem + i = 'foo';

is not valid.  There are several ways to do what you want, none of
them good.  Use implicit iteration from the jquery selectors instead.
Stop using id's when you have an unknown or changing number of items
you are iterating through to do things.  IDs should only be used for
unique items.  When you have a list of similiar items doing the same
thing, give them all the same class or custom attribute and let jQuery
do the iterating for you.

Josh Powell


On Aug 30, 12:37 am, "Michael Geary" <m...@mg.to> wrote:
> Something I forgot to mention in my previous reply... To make sure it's
> clear what code is actually being run in the browser, never rely on looking
> at your JSP source to understand it. That's what threw you off here. The
> browser never sees your JSP source, only the HTML/JS/CSS/whatever files that
> your JSP generates.
>
> Do you have Fiddler? If not, go get it right now and get familiar with it:
>
> http://www.fiddler2.com/
>
> It looks like you're using Windows 2000; Fiddler is supposed to run OK there
> if you have the .NET Framework 2.0.
>
> Fiddler's inspectors are great for examining all of the actual data
> downloaded to your browser. You can of course use other tools such as the
> Web Developer Toolbar and even a View Source for the .html file. But Fiddler
> is terrific.
>
> The main thing is that when you're debugging anything in the browser, you
> have to forget about the JSP source and think only in terms of what the
> browser actually receives.
>
> -Mike
>
> > From: kali
>
> > this works in JSP:
>
> > <%  for (int i = 1; i < 5; i++) { %>
> >   $('#image<%=i%>').bind('mouseover',function(event) {
> >         $('#image<%=i%>').addClass('dim');
> >     });
> > <% } %>
>
> > but the same thing, in JavaScript, doesn't work:
>
> > for (i = 1; i < 5; i++) {
> >   $('#thumb' + i).bind('mouseover',function(event) {
> >      $('#thumb' + i).addClass('dim');
> >   });
> > }

Reply via email to