2012-02-21 33 views
9

我有一個鏈接。當有人點擊時,我想在讓它工作之前檢查一些條件。如果是false,應該防止默認操作。如果a等於1如果條件錯誤,則防止默認

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

鏈接應該只工作。上面的代碼是否正確。如果滿足特定條件,則將a設置爲1。只有滿足條件,鏈接才能工作。

+4

*是上面的代碼正確*你問這個幹什麼?你有問題嗎?如果是,哪些? – 2012-02-21 10:41:47

+0

什麼是'a'?你可以在你的代碼中發佈它嗎? – elclanrs 2012-02-21 10:42:43

+3

請注意,'=='和'==='之間有區別。如果你想檢查'a'是否等於整數'1',那麼你應該使用'a === 1'。請參閱http://stackoverflow.com/questions/359494/javascript-vs-does-it-matter-which-equal-operator-i-use瞭解其差異。 – 2012-02-21 10:45:10

回答

9

通過假設「如果等於1應只工作」你的意思是a元素的文本等於1,試試這個:

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

你可以修改text()使用的任何屬性的元素在jQuery中可用。

UPDATE

我一個是保持爲0,直到條件滿足一個變種。

在這種情況下,問題只是你平等運營商是不正確的:

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

我的a是一個變量,它保持值0直到滿足條件。 – esafwan 2012-02-21 10:59:27

+1

啊,我明白了,在這種情況下,我已經更新了我的答案。 – 2012-02-21 11:01:37

+1

爲了不讓自己困惑,可能值得使用'true'和'false'而不是'0'和'1'。 – 2012-02-21 11:03:58

3

注意:

!a計算結果爲真或假。如果將a轉換爲布爾值爲true,則!a的計算結果爲false。

所有正整數的計算公式爲true。因此!a將評估爲false。使用雙等於==到1的比較將使用布爾值1true測試布爾!a。所以如果a是一個正整數,因爲我懷疑它是那麼你的if聲明將總是評估爲false。

如果你想測試是不是別的東西,你需要改變比較運算符(===)中的第一個等於!

E.g. var a = 2; if(a!==1) { // do something } < - A是2,因此如果比較結果爲真,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(); 
} 
+0

非常感謝,這是非常全面的解釋。學到的東西比我問的要多得多。 – esafwan 2012-02-21 12:37:57