I'm looking for a way to replace the image in the featured-image class with the image one clicks in the thumbnail class . I want to implement this using jquery ... I have been trying to use the $(selector).replaceWith() function but that doesnt work as expected. Below is my markup
<div class = "image-slider">
<div id = "featured-image">
<img src = "truck.jpg">
</div>
<ul class = "thumbnail">
<li><img class = "small-image" src = "images/1.jpg" ></li>
<li><img class = "small-image" src = "images/2.jpg" ></li>
<li><img class = "small-image" src = "images/3.jpg" ></li>
<li><img class = "small-image" src = "images/4.jpg" ></li>
<li><img class = "small-image" src = "images/5.jpg" ></li>
</ul>
</div>
Anyone with a solution that works without removing the clicked item from the unordered list? The solution should also allow one to switch the image multiple times. Thank you.
你可以使用$(selector).html("html string here")
,或者可以传递一个html节点
You can do something like this... Replace src of image in featured-image class on clicking image from thumbnail class.
$('.thumbnail img').click(function(){
var imgSrc = $(this).attr('src');
$('#featured-image img').attr('src',imgSrc);
})
$('.thumbnail img').on('click', function(e) {
var _el = $(e.currentTarget);
$('#featured-image img').attr('src', _el.attr('src'));
});
You can change the attribute src
with jquerys .attr()
function. Example: $(selector).attr("src", "your image file");
Here's a reference .
You can also set an attribute to help you determine what image you would like to swap out to help make the jquery a bit more readable.
<div class="image-slider">
<div id="featured-image">
<img src="//image.flaticon.com/icons/svg/147/147127.svg" height="250">
</div>
<ul class="thumbnail">
<li><img class="vehicle" vehicletype="bus" src="//image.flaticon.com/icons/svg/147/147125.svg" height="50"></li>
<li><img class="vehicle" vehicletype="ambulance" src="http://image.flaticon.com/icons/svg/119/119083.svg" height="50"></li>
<li><img class="vehicle" vehicletype="taxi" src="http://image.flaticon.com/icons/svg/147/147123.svg" height="50"></li>
</ul>
</div>
$(document).ready(function (){
$(".vehicle").on('click', function(){
if($(this).attr("vehicletype") == "bus")
{
$("#featured-image").html("<img src='//image.flaticon.com/icons/svg/147/147125.svg' height='250' />");
}
else if ($(this).attr("vehicletype") == "ambulance")
{
$("#featured-image").html("<img src='http://image.flaticon.com/icons/svg/119/119083.svg' height='250' />");
}
else if ($(this).attr("vehicletype") == "taxi")
{
$("#featured-image").html("<img src='http://image.flaticon.com/icons/svg/147/147123.svg' height='250' />");
}
});
});
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.