2016-08-04 89 views
0

我正在面臨觸發jquery點擊功能的問題。我想用jquery隱藏電話號碼和電子郵件。電話號碼和電子郵件只能看到是否使用點擊<p>標籤。點擊時jquery點擊功能不起作用

下面是我已經寫過的jquery函數;

function() { 
    var $phone = '123456123', 
     $email = '[email protected]', 
     phone = $('#phone'), 
     email = $('#email'); 

    $(phone).click(function() { 
     var text = $(this).text() == $phone ? 
      'Click to view number' : $phone; 
     $(this).text(text).toggleClass("active"); 
    }); 

    $(email).click(function() { 
     var text = $(this).text() == $email ? 
      'Click to view email' : $email; 
     $(this).text(text).toggleClass("active"); 
    }); 

}();  

當我運行代碼時,我點擊數字標籤,但沒有任何改變。

+1

什麼是不工作的有關您的代碼?您是否收到特定的錯誤訊息?它是否加載,然後不做任何事情?請閱讀以下關於如何在此網站上提出問題的文章:http://stackoverflow.com/help/how-to-ask –

+0

「active」類的css代碼在哪裏?你有沒有css,當它不活動? – Jodes

+0

使用'$('#phone')。click()'或'phone.click()' - 您不需要額外的「$」。 – ldg

回答

1

只是需要在JS小的修補程序。 看到它的工作here

$(function() { 
    var $phone = '123456123', 
      $email = '[email protected]', 
      phone = $('#phone'), 
       email = $('#email'); 

    $(phone).click(function() { 
     var text = $(this).text() == $phone ? 
      'Click to view number' : $phone; 
     $(this).text(text).toggleClass("active"); 
    }); 

    $(email).click(function() { 
     var text = $(this).text() == $email ? 
      'Click to view email' : $email; 
     $(this).text(text).toggleClass("active"); 
    }); 
});  
+0

這是工作,謝謝。我在美元符號後工作就像我想要的一樣。 –

3

你的代碼是這樣的:

function() { 
    // code 
}(); 

IIFEs不工作的方式。將函數包裝成()s:

(function() { 
    // code 
})(); 

它可以工作。

您還有other ways「激活」功能。最好的風格取決於爭論。我所推薦的是選擇一個並持續使用它。

See jsbin demo here.

+0

謝謝更正:) –