【问题标题】:If conditions false then prevent default如果条件为假,则阻止默认
【发布时间】:2012-03-11 16:14:22
【问题描述】:

我有一个链接。当有人点击它时,我想在让它工作之前检查一些条件。如果是false,则应阻止默认操作。

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

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

【问题讨论】:

  • 上面的代码是否正确 为什么要问?你有问题吗?如果是,是哪些?
  • 请注意,===== 之间存在差异。如果你想检查a是否等于整数1,那么你应该使用a===1。请参阅stackoverflow.com/questions/359494/… 了解区别。
  • 根据您的解释,我认为您的意思是 a != 1 而不是 !a == 1
  • 哈哈抓住了它。 Mathias Bynens 是对的,我很确定这是您的问题,但也可能是类型比较错误。

标签: javascript jquery conditional preventdefault


【解决方案1】:

假设 'should only work if a is equal to 1' 你的意思是 a 元素的文本等于 1,试试这个:

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

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

更新

my a 是一个 var,在满足条件之前保持值为 0。

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

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

【讨论】:

  • my a 是一个 var,在满足条件之前保持值 0。
  • 为了不让自己感到困惑,使用truefalse 代替01 可能是值得的。
【解决方案2】:

小心:

!a 计算结果为真或假。如果将a 转换为布尔值是true,则!a 的计算结果为false。

所有正整数的计算结果为true。所以!a 将评估为假。使用双等于 == 与 1 的比较将测试布尔值 !a 与布尔值 1true。因此,如果 a 是我怀疑的正整数,那么您的 if 语句将始终评估为 false。

如果您想测试 is something is NOT something else,您需要将比较运算符 (===) 中的第一个等号更改为 !

例如var a = 2; if(a!==1) { // do something } 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
}

希望有帮助

附:记住你的比较运算符:

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

更新

我看到你对另一篇帖子的评论说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();
}

【讨论】:

  • 非常感谢这是非常全面的解释。学到的比我问的要多。
猜你喜欢
  • 2019-10-10
  • 2023-04-05
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2020-03-06
  • 2016-10-16
  • 1970-01-01
相关资源
最近更新 更多