开发者

How to switch image based on anchor tag using jQuery?

开发者 https://www.devze.com 2022-12-18 15:57 出处:网络
I have a lists of thumbnail images. When user clicks a small thumbnail imag开发者_C百科e, it swaps it to show the full image.

I have a lists of thumbnail images. When user clicks a small thumbnail imag开发者_C百科e, it swaps it to show the full image. I have been trying to get the anchor tag name so that I can explode the value i. But I can't get it working, any ideas?

My javascript:

function swap(image) {
   document.getElementById("main").src = image.href;
}

My HTML & PHP script:

<img id="main" src="images/main.jpg" width="226" height="226" alt="" />

<p><strong>Day <?php echo $i; ?>:</strong></strong><br /><?php echo $today[$i]; ?></p>
</div>
</div>

<?php
 for($i=1; $i<$day; $i++)
   {
     echo'<a href="images/prevDay-'.$i.'.jpg" name="day-'.$i.'" onclick="swap(this); return false;">';
     echo'<img src="images/thumbDay-'.$i.'.jpg" width="50" height="50" alt="" title="thumbDay-'.$i.'.jpg" /></a> ';
   }
?>


You'd be better giving it an ID instead or as well.

Accessing in jQuery then would be (for example):

$("#day-1")

Or without jQuery, just using your document.getElementById.

If you really want to get it by name:

$("a[name='day-1']")


assuming you attribute class "thumbnail" for thumbnails, you may do

$(".thumbnail").click(function(){
   // $(this) refers to the clicked element
   $("#main").attr("src", $(this).attr("href"))

})

Note the use of attr() method as getter and setter

// getter:
$(selector).attr(attr_name) 

// setter
$(selector).attr(attr_name, attr_value) 

Your PHP can be re-written as:

// no need for <a> element
<?php
 for($i=1; $i<$day; $i++)
   {
     echo'<img class="thumbnail" src="images/thumbDay-'.$i.'.jpg" width="50" height="50" alt="" title="thumbDay-'.$i.'.jpg" />';
   }
?>
0

精彩评论

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