I have this HTML / PHP code that displays multiple images.
<div class="product-other-images">
<?php
for($i = 0; $i < sizeof($productImages); $i++)
{
echo '<a id="alternate-image" href="#"';
if($i == 0)
echo 'class="active"';
echo '><img alt="' . $productName . '" src="' . $productImages[$i][1] . '"></a>';
}
?>
</div>
When you click the a href, I want to select the src from the img on the inside. So far I have this code which works when I click the a href.
var Item = function () {
return {
init: function () {
$(document).ready(function () {
$('a').click(function () {
if ($(this).prop('id') == 'alternate-image')
{
var href = $(this).attr('href');
alert(href);
}
});
});
}
};
}();
I need to take the src from the image and change the main display image of another img src.
Should I just make the img src the jQuery trigger?
The img
is a child of the a
element so
$('a').click(function () {
if (this.id == 'alternate-image') {
var src= $(this).find('img').attr('src');
alert(src);
}
});
You are creating the elements in a loop, so you are creating multiple elements with the same id that is not a valid html structure as id of an element must be unique.
In your case instead of using alternate-image
as id use it as a class then use class selector to target those elements like
$('a.alternate-image').click(function () {
var href = $(this).find().attr('href');
alert(href);
});
then
<div class="product-other-images">
<?php
for($i = 0; $i < sizeof($productImages); $i++)
{
echo '<a class="alternate-image" href="#"';
if($i == 0)
echo 'class="active"';
echo '><img alt="' . $productName . '" src="' . $productImages[$i][1] . '"></a>';
}
?>
</div>
You can't duplicate ID's in a page so change the id to class.
Then you can target the elements with the class as selector:
$('.alternate-image').click(function(e){
e.preventDefault();// prevent default behavior of <a>
var src = $(this).find('img').attr('src');
})
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.