如果条件为false则阻止默认

我有一个链接。 当有人点击它时我想检查一些条件然后让它工作。 如果为false则应该阻止默认操作。

 $(".pager-next a.active").click(function(event) { if (!a == 1) { event.preventDefault(); } }); 

该链接仅在a等于1时才有效。 以上代码是否正确。 如果满足特定条件,则a设置为1 。 该链接仅在满足条件时才有效。

假设’ 应该仅在a等于1时起作用 ‘表示a元素的文本等于1,试试这个:

 $(".pager-next a.active").click(function(event) { if ($(this).text() != "1") { event.preventDefault(); } }); 

您可以修改text()以使用jQuery中可用的元素属性。

UPDATE

我的a是一个var,它保持值0直到满足条件。

在这种情况下,问题只是您的相等运算符不正确:

 $(".pager-next a.active").click(function(event) { if (a != 1) { event.preventDefault(); } }); 

小心:

!a评估为真或假。 如果将a转换为bool为true那么!a计算结果为false。

所有正整数都评估为true 。 所以!a会评估为假。 使用double equals ==到1的比较将测试boolean !a与布尔值1true 。 因此,如果a是一个正整数,因为我怀疑它是if语句将始终评估为false。

如果你想测试的东西不是别的东西你需要改变你的比较运算符( === )中的第一个等于!

例如var a = 2; if(a!==1) { // do something } var a = 2; if(a!==1) { // do something } < - A是2,因此if比较wille评估为true,因为a 等于1

在您的代码中,我们有:

 var a = 2; if(!a==1){ // a was 2 (or boolean true by default) // but using ! has negated its boolean value // so !a evaluates to boolean false // which is being compared to 1 (evaluating to boolean true) // so this if statement will never get here } 

希望有所帮助

PS记住您的比较运算符:

 !"hello world" == 0 // true !"hello world" === 0 // false 

更新

我看到你对另一篇post的评论,其中a表示a0直到有事情发生,然后是1

在这种情况下:

 var a = 0; // integer 0 or bool false if(!a==1){ // if the bool opposite of 0 (false) is equal to 1 (true) // well, opposite of false is true, so you're checking if true is equal to true // so this will get called e.preventDefault(); }