Javascript if 语句无法正常工作
//this counts how many images exist
var img_count = $("#gallery_scroller img").length;
//this is a number where I want the clicks to stop working
var limit_count = img_count/3;
var click_count = 1;
if ( limit_count > click_count){
$("#down_arrow").click(function(){
click_count++
var css_position = -1*click_count*300;
$('#gallery_scroller img').css('top', css_position);
alert(css_position+' '+limit_count+' '+click_count);
});
};
我将警报放在最后,以便每次单击时都可以观察到值。即使 click_count 大于 limit_count,它也会继续进行。在 if 条件下,当我将 click_count 替换为大于 limit_count 的实际数字时,它会起作用。
//this counts how many images exist
var img_count = $("#gallery_scroller img").length;
//this is a number where I want the clicks to stop working
var limit_count = img_count/3;
var click_count = 1;
if ( limit_count > click_count){
$("#down_arrow").click(function(){
click_count++
var css_position = -1*click_count*300;
$('#gallery_scroller img').css('top', css_position);
alert(css_position+' '+limit_count+' '+click_count);
});
};
I put the alert at the end so I can observe the values everytime I click. It just keeps on going even though the click_count is larger than the limit_count. In the if condition, when I replace click_count with an actual number that is larger than the limit_count it works.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
您的
if
语句不在click
事件处理程序的代码中。附加处理程序后,只有处理程序内的代码会在单击发生时运行。我不完全确定您想要的结果是什么,但这可能更接近:
例如,将测试放在事件处理程序代码中。
旁注:
if
块上的大括号末尾不需要分号,例如:旁注 2:我在
click_count++
之后添加了分号。如果没有它,您将依赖于自动分号插入这一可怕的东西。你没问题,因为后面有一个换行符,但总的来说,最好学习分号的规则,并始终将它们包含在需要的地方。Your
if
statement isn't in the code in theclick
event handler. Once the handler is attached, only the code within the handler will get run when the click occurs.I'm not entirely sure what your desired result is, but this is probably closer:
E.g., put the test within the event handler code.
Side note: There's no need for a semicolon at the end of the curly braces on an
if
block, e.g.:Side note 2: I've added a semicolon after
click_count++
. Without it, you're relying on the horror that is automatic semicolon insertion. You were okay because there was a line break after it, but in general, best to learn the rules of where semicolons go and always include them where they're required.您的条件需要位于事件处理程序内:
your condition needs to be inside the event handler: