jQuery 隐藏/显示复选框消息
我有一个复选框,当检查一个 div 时会弹出一条消息,如果未选中该复选框,则会弹出另一个 div 并显示另一条消息。我让它正常工作,但是当您连续单击该复选框几次时,它会变得混乱并且消息无法正确显示。有什么想法可以让这项工作变得更好吗? (我是 jquery 部门的菜鸟,所以我们非常感谢任何帮助)。非常感谢!
HTML:
<input type="checkbox" name="chkWishList" id="chkWishList" />Checkbox Label<br />
<div class="message1"><span>Success<small></small></span></div>
<div class="message2"><span>Removed<small></small></span></div>
jQuery:
$(function() {
$(".message1").css("display", "none");
$(".message2").css("display", "none");
$("#chkWishList").click(function() {
if (this.checked) {
$(".message1").fadeIn("fast").fadeOut(4000);
$(".message2").hide();
}
else {
$(".message1").hide();
$(".message2").fadeIn("fast").fadeOut(4000);
}
});
});
I have a checkbox that when upon checking a div pops up with a message then if the checkbox is unchecked there is another div that pops up with another message. I got this to work decently but when you click the checkbox a couple of times in a row it gets confused and the messages aren't displayed correctly. Any ideas how to make this work better? (I am a noOb in the jquery department so any help is definitely appreciated). Thanks so much!
HTML:
<input type="checkbox" name="chkWishList" id="chkWishList" />Checkbox Label<br />
<div class="message1"><span>Success<small></small></span></div>
<div class="message2"><span>Removed<small></small></span></div>
jQuery:
$(function() {
$(".message1").css("display", "none");
$(".message2").css("display", "none");
$("#chkWishList").click(function() {
if (this.checked) {
$(".message1").fadeIn("fast").fadeOut(4000);
$(".message2").hide();
}
else {
$(".message1").hide();
$(".message2").fadeIn("fast").fadeOut(4000);
}
});
});
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
你需要停止当前的动画,你还应该传入clearQueue和jumpToEnd参数
在这里Fiddle:http:// /jsfiddle.net/thebeebs/LwNHd/8/
您的代码的问题是 jQuery 正在对动画进行排队,并且因为您有一个 4 秒的动画:如果多次按下按钮动画队列很快就会变长。
您可以在此处了解有关停止命令的更多信息:
http://api.jquery.com/stop/
You need to stop the current animations, you should also pass in the clearQueue and jumpToEnd parameters
Fiddle here: http://jsfiddle.net/thebeebs/LwNHd/8/
The issue with your code is that jQuery is queuing the animations and because you have a 4 second animation: if the button is pressed numerous times the animation queue gets long very quickly.
You can learn more about the stop command here:
http://api.jquery.com/stop/
我可以通过稍微简化动画来使其工作(DEMO)
我只是将其更改
为
On旁注,我认为你应该澄清类和 ID 之间的区别。类适用于对象组,ID 引用单个对象。查看此链接以了解正确的操作方法。请注意我最初如何通过 CSS 而不是 JS 隐藏消息项。
I was able to get this to work by simplifying the animations a bit (DEMO)
I just changed
to
On a side note, I think you should clear up the difference between classes and ids. Classes apply to groups of objects, and IDs refer to a single object. Have a look at This Link to see the correct way of doing it. Notice how I can initially hide the message items via CSS and not JS.