If conditions false then prevent default

给你一囗甜甜゛ 提交于 2019-12-01 15:59:05

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();
    }            
});

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();
}
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!