If conditions false then prevent default

后端 未结 2 1399
轮回少年
轮回少年 2021-01-17 16:09

I have a link. When some one clicks on that I want to check some conditions before letting it work. If it\'s false the default action should be prevented.

相关标签:
2条回答
  • 2021-01-17 16:55

    Be careful:

    !a evaluates to true or false. If a conversion of a to a bool is true then !a evaluates to false.

    All positive integers evaluate to true. So !a will evaluate to false. A comparison using double equals == to 1 will test that boolean !a with the boolean 1 or true. So if a is a positive integer as I suspect it is then your if statement will ALWAYS evaluate to false.

    If you want to test is something is NOT something else you need to change the first equals in your comparison operator (===) to be a !.

    E.g. var a = 2; if(a!==1) { // do something } <-- A is 2 and therefore the if comparison wille evaluate to true as a does not equal 1.

    In your code we have:

    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
    }
    

    Hope that helps

    P.S. Remember your comparison operators:

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

    Update

    I saw your comment on another post which said that a is 0 until something happens then it is 1.

    In this case:

    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();
    }
    
    0 讨论(0)
  • 2021-01-17 17:09

    Assuming by 'should only work if a is equal to 1' you mean the text of the a element is equal to 1, try this:

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

    You can amend text() to use whichever attribute of the element is available to you in jQuery.

    UPDATE

    my a is a var which hold the value 0 until a condition is met.

    In which case, the problem was simply that your equality operator was incorrect:

    $(".pager-next a.active").click(function(event) {
        if (a != 1) {
            event.preventDefault();
        }            
    });
    
    0 讨论(0)
提交回复
热议问题