-我是jQuery免责声明的新手-
我有两张图片:
https://i.imgur.com/l2H17fn.jpg
https://i.imgur.com/5nlOoyc.jpg
在五次点击了 次之后,我想显示第二个代替第一个。
要使图像在单击后即可替换,我要这样做:
HTML:
<div class = "dog">
<img id="happy" src="https://i.imgur.com/l2H17fn.jpg">
</div>
jQUERY:
$('.dog').click(function(e){
e.preventDefault();
$("#happy").attr('src',"https://i.imgur.com/5nlOoyc.jpg");
return false;
});
现在,如果我想在第五次单击后替换图像怎么办?那会是什么样?
答案 0 :(得分:2)
您可以使用变量来跟踪点击次数:
// initialize click count to zero.
var clicks = 0;
$('.dog').on('click', function() {
// increment click count.
clicks++;
// FOR DEMO - output the click count to the console.
// console.log(clicks);
// if clicks is greater than or equal to 5...
if (clicks >= 5) {
// ... change the image ...
$("#happy").attr('src', "https://i.imgur.com/5nlOoyc.jpg");
// .. and remove this click handler.
$(this).off('click');
}
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div class="dog">
<img id="happy" src="https://i.imgur.com/l2H17fn.jpg">
</div>
答案 1 :(得分:1)
你在这里...我认为诀窍是要有一个全局信号量变量...尽管这是一个切换...:)
var clicks = 0;
$('.dog').on('click', function(e){
clicks++;
if(clicks >= 5){
if($('#happy').attr('src') !== 'https://i.imgur.com/5nlOoyc.jpg'){
$("#happy").attr('src',"https://i.imgur.com/5nlOoyc.jpg");
}else{
$("#happy").attr('src',"https://i.imgur.com/l2H17fn.jpg");
}
clicks = 0;
}
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div class = "dog">
<img id="happy" src="https://i.imgur.com/l2H17fn.jpg">
</div>