当用户点击其他图片时,我想更改所选(或默认)图像。我尝试使用以下代码,但是没有工作..我在哪里错误?
以下是简单的jquery代码;
<script>
$('img.thumbnail').click(function () {
$('#productImage').attr('src',$(this).attr('src').replace('60/60','400/200'));
})
</script>
和html;
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script>
<div class="col-md-5">
<img id="productImage" src='http://via.placeholder.com/400/200?text={{$product->product_name}}'>
<hr>
<div class="row">
<div class="col-xs-3">
<a href="#" class="thumbnail"><img src="http://via.placeholder.com/60/60?text=otherimage1"></a>
</div>
<div class="col-xs-3">
<a href="#" class="thumbnail"><img src="http://via.placeholder.com/60/60?text=otherimage2"></a>
</div>
<div class="col-xs-3">
<a href="#" class="thumbnail"><img src="http://via.placeholder.com/60/60?text=otherimage3"></a>
</div>
</div>
答案 0 :(得分:2)
您的img
不包含课程.thumbnail
,就像这样,
$('.thumbnail img').click(function () {
$('#productImage').attr('src', $(this).attr('src').replace('60/60','400/200'));
});
并检查您的<img>
代码。
答案 1 :(得分:1)
你没有调用正确的选择器。
$('a.thumbnail').click(function () {
$('#productImage').attr('src',$(this).children('img').attr('src').replace('60/60','400/200'));
})
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script>
<div class="col-md-5">
<img id="productImage" src='https://via.placeholder.com/400/200?text=nothing'>
<hr>
<div class="row">
<div class="col-xs-3">
<a href="javascript:void(0)" class="thumbnail"><img src="https://via.placeholder.com/60/60?text=otherimage1"></a>
</div>
<div class="col-xs-3">
<a href="javascript:void(0)" class="thumbnail"><img src="https://via.placeholder.com/60/60?text=otherimage2"></a>
</div>
<div class="col-xs-3">
<a href="javascript:void(0)" class="thumbnail"><img src="https://via.placeholder.com/60/60?text=otherimage3"></a>
</div>
</div>
答案 2 :(得分:1)
尝试将点击事件附加到a.thumbnail
元素,然后执行jQuery.find('img')以获取缩略图图片的src
属性:
$('a.thumbnail').click(function () {
var src = $(this).find('img').attr('src').replace('60/60','400/200');
$('#productImage').attr('src', src);
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script>
<div class="col-md-5">
<img id="productImage" src="http://via.placeholder.com/400/200?text=otherimage0">
<hr>
<div class="row">
<div class="col-xs-3">
<a href="#" class="thumbnail"><img src="http://via.placeholder.com/60/60?text=UrunResimi1"></a>
</div>
<div class="col-xs-3">
<a href="#" class="thumbnail"><img src="http://via.placeholder.com/60/60?text=otherimage2"></a>
</div>
<div class="col-xs-3">
<a href="#" class="thumbnail"><img src="http://via.placeholder.com/60/60?text=otherimage3"></a>
</div>
</div>
答案 3 :(得分:0)
$(document).ready(function(){
$('.thumbnail img').click(function () {
$('#productImage').attr('src',$(this).attr('src').replace('60/60','400/200'));
});
});
您的jquery选择器不正确。它应采用这种格式,并确保您拥有document.ready功能,以使其在所有浏览器中在线或离线正常工作。