有没有办法在单击锚点时在两个值之间切换图像的src属性?
像这样:
$('a#some-anchor').click(function() {
// code here that toggles between two image src's e.g. "images/some-image1.jpg" and "images/some-image2.jpg"
});
答案 0 :(得分:7)
$("img").bind("click", function() {
var src = ($(this).attr("src") === "img1_on.jpg")
? "img2_on.jpg"
: "img1_on.jpg";
$(this).attr("src", src);
});
从这里采取:
答案 1 :(得分:2)
使用内部data()
功能可以起作用:
$('a#some-anchor').click(function() {
var img = $(this);
if ( img.data('active') ) {
img.attr('src', 'images/some-image1.jpg');
img.data('active', false);
} else {
img.attr('src', 'images/some-image2.jpg');
img.data('active', true);
}
});
答案 2 :(得分:2)
不知道你的形象在哪里,但是:
$('a#some-anchor').click(function() {
var img = $('selector');
if (img.attr('src').match(/image1/)) {
img.attr('src', 'images/some-image2.jpg');
} else {
img.attr('src', 'images/some-image1.jpg');
}
});
答案 3 :(得分:1)
$('a#some-anchor').click(function() {
var img = $('#yourIMG');
var img1 = "images/some-image1.jpg";
var img2 = "images/some-image2.jpg";
img.attr('src', img.attr('src') == img1 ? img2 : img1);
});
答案 4 :(得分:0)
查看此代码段:
var plus = 'https://d30y9cdsu7xlg0.cloudfront.net/png/5805-200.png';
var minus = 'https://d30y9cdsu7xlg0.cloudfront.net/png/5802-200.png';
$('#magic-toggle').click(function() {
if ($('.fun-img').attr('src') === plus) {
$('.fun-img').attr('src', minus);
} else {
$('.fun-img').attr('src', plus)
}
})
.fun-img {
width: 80px;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<img src="https://d30y9cdsu7xlg0.cloudfront.net/png/5805-200.png" class="fun-img" id="magic-toggle">