仅当满足可变条件时 jQuery onclick
我有一个按钮,当单击该按钮时,仅当具有“like”类的 div 数量大于 0 时才应执行其代码。问题是,即使这是真的,该按钮仍然不会执行其代码。请注意,我尝试了 .length 和 .size() 以获得相同的结果。
$(document).ready(function() {
countlikes = $('[id^=post_].like').length;
likestatus = 1;
$('#show_likes').on('click', function() {
if (countlikes >0) {
likestatus++;
$('[id^=post_].like').toggle();
if (likestatus % 2 == 0) {
$('#hidelikedbtn').removeClass('hidelikedimgoff').addClass('hidelikedimgon');
} else {
$('#hidelikedbtn').removeClass('hidelikedimgon').addClass('hidelikedimgoff');
}
return false;
} else {
return false;
}
});
});
有什么想法吗?
I have a button that when clicked, should only execute its code if the number of div that have the class of "like" is greater than 0. The problem is that even if this is true, the button still won't execute its code. Note that I have tried both .length and .size() to the same result.
$(document).ready(function() {
countlikes = $('[id^=post_].like').length;
likestatus = 1;
$('#show_likes').on('click', function() {
if (countlikes >0) {
likestatus++;
$('[id^=post_].like').toggle();
if (likestatus % 2 == 0) {
$('#hidelikedbtn').removeClass('hidelikedimgoff').addClass('hidelikedimgon');
} else {
$('#hidelikedbtn').removeClass('hidelikedimgon').addClass('hidelikedimgoff');
}
return false;
} else {
return false;
}
});
});
Any ideas?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
假设页面加载后“like”类的元素数量发生变化,问题是您当前仅在点击处理程序之外为
countlikes
分配一次值,因此,每次处理程序运行时,它将使用原始的 countlikes 值,而不是当前计数。将分配移至处理程序内,它应该可以工作。 (尽管考虑到该变量目前仅在一个地方实际使用,但您实际上并不需要它,您可以直接测试$('[id^=post_].like').length
在你的 if 语句中。)另外你的问题说“大于 1”而你的代码说“> 0”,所以即使它有效,它也不会做你所描述的事情。
另外,与您的问题无关,最后一个
else
情况是多余的:在if
末尾返回 false,而在 else 中返回 false,所以为什么不直接将return false;
移到 if 之外并删除 else?Assuming that the number of elements with "like" class varies after the page loads, the problem is that you currently assign a value to
countlikes
only once, outside your click handler, so every time the handler runs it will be using the originalcountlikes
value and not a current count. Move the assignment inside the handler and it should work. (Though given the variable is only actually used in one place at the moment you don't really need it, you can just test$('[id^=post_].like').length
directly in your if statement.)Also your question says "greater than 1" and your code says "> 0", so even if it worked it wouldn't be doing what you describe.
Also, unrelated to your problem, the last
else
case is redundant: at the end of theif
you return false, and in the else you return false, so why not just move thereturn false;
outside the if and delete the else?您需要在“countlike”变量前面添加一个
var
。此外,您还需要在其他变量前面添加相同的内容。
You need a
var
in front of your 'countlike' variable.Also, you'll need the same thing in front of your other variable.