如果条件为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
与布尔值1
或true
。 因此,如果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表示a
为0
直到有事情发生,然后是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(); }