我正在尝试创建一个包含三个div的块,单击它们将交换图像。到目前为止,我有这个...
$( ".button1" ).click(function() {
$(this).attr("src","https://dummyimage.com/100x100/000000/fff&text=1-on")
});
$( ".button2" ).click(function() {
$(this).attr("src","https://dummyimage.com/100x100/000000/fff&text=2-on")
});
$( ".button3" ).click(function() {
$(this).attr("src","https://dummyimage.com/100x100/000000/fff&text=3-on")
});

<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="button1">
<img src="https://dummyimage.com/100x100/000000/fff&text=1-off">
</div>
<div class="button2">
<img src="https://dummyimage.com/100x100/000000/fff&text=2-off">
</div>
<div class="button3">
<img src="https://dummyimage.com/100x100/000000/fff&text=3-off">
</div>
&#13;
这对我不起作用,是否有人有类似的例子可以指出我?
我也只想要一个&#39; on&#39;要一次显示的图像,以便其他人在打开时关闭。
答案 0 :(得分:2)
为所有div提供相同的类,然后创建一个click
事件,该事件将切换当前的img,同时关闭其他人:
$('.button img').click(function() {
var src = $(this).attr('src');
$(this).attr('src', src.replace('-off', '-on')); //change off to on
$('img').not(this).attr('src', function(_, src) { //change on to off
return src.replace('-on', '-off');
});
});
<强>段:强>
$('.button img').click(function() {
var src = $(this).attr('src');
$(this).attr('src', src.replace('-off', '-on')); //change off to on
$('img').not(this).attr('src', function(_, src) { //change on to off
return src.replace('-on', '-off');
});
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="button">
<img src="https://dummyimage.com/100x100/000000/fff&text=1-off">
</div>
<div class="button">
<img src="https://dummyimage.com/100x100/000000/fff&text=2-off">
</div>
<div class="button">
<img src="https://dummyimage.com/100x100/000000/fff&text=3-off">
</div>
答案 1 :(得分:0)
您定位的是父级而不是img。
尝试.class img
例如:
$( ".button1 img" ).click(function() {
$(this).attr("src","https://dummyimage.com/100x100/000000/fff&text=1-on")
});
这将选择图像,而不是父div。
答案 2 :(得分:0)
$(this).attr(
应该是
$(this).find('img').attr(