SitePoint Sponsor

User Tag List

Results 1 to 2 of 2
  1. #1
    SitePoint Enthusiast
    Join Date
    Jul 2002
    Posts
    95
    Mentioned
    0 Post(s)
    Tagged
    0 Thread(s)

    Problem with a for loop and storing into variables

    This works OK:

    -----------------------------------------------------------------------
    <img src="minimiraj.jpg" id="slika1">
    <img src="zapri.jpg" id="slika2">
    <img src="povecaj.jpg" id="slika3">
    <img src="pomanjsaj.jpg" id="slika4">

    for (var i = 1; i < 5; i++) {
    document.getElementById('slika' + i).onclick = function() {
    alert('ouch!');}}
    -----------------------------------------------------------------------


    But this doesn't:
    -----------------------------------------------------------------------
    <img src="minimiraj.jpg" id="slika1">
    <img src="zapri.jpg" id="slika2">
    <img src="povecaj.jpg" id="slika3">
    <img src="pomanjsaj.jpg" id="slika4">

    for (var i = 1; i < 5; i++) {
    document.getElementById('slika' + i).onclick = function() {
    alert(document.getElementById('slika' + i).src);}}
    ------------------------------------------------------------------------



    I think it's because the for loop in this case doesn't store the function as:
    alert(document.getElementById('slikai').src
    but as
    alert(document.getElementById('slika' + i).src
    and since there is no
    id="slika + i" :>
    the function doesn't work.

    Am I right?
    And how can I solve this?

  2. #2
    Currently Occupied; Till Sunda Andrew-J2000's Avatar
    Join Date
    Aug 2001
    Location
    London
    Posts
    2,475
    Mentioned
    0 Post(s)
    Tagged
    0 Thread(s)
    you wasn't passing the reference of the object along this will solve this.

    PHP Code:
    <img src="minimiraj.jpg" id="slika1">
    <
    img src="zapri.jpg" id="slika2">
    <
    img src="povecaj.jpg" id="slika3">
    <
    img src="pomanjsaj.jpg" id="slika4">

    <
    script type="text/javascript">
    for (var 
    15i++)
    {
      
    document.getElementById('slika' i);
      
    x.onclick = function(i)
                  {
                    
    alert(x.src);
                  }
    }
    </script> 


Bookmarks

Posting Permissions

  • You may not post new threads
  • You may not post replies
  • You may not post attachments
  • You may not edit your posts
  •