2012-10-04 30 views
0

我的代碼的最初部分正在工作。它加載-標誌,然後在單擊時更改爲+標誌。或者,如果需要,它可以加載多個+標誌。無論哪種方式,第一次初始加載都很好。問題出在點擊事件上。它根本不起作用。我的切換已損壞。你能幫助解決它嗎?

$(document).ready(function() { 
    if ($('.user-email').length == 1) { 
     $('.user-email .section-icon').toggleClass('open'); 
     $('.section-icon').text('-'); 
    } else if ($('.user-email').length > 1) { 
     $('.section-icon').text('+'); 
    } 

    $('.user-email-text').click(function(event) { 
     event.preventDefault(); 
     if ($(".section-icon:contains('-')")) { 
      $('.section-icon').text('+'); 
     } else if ($(".section-icon:contains('+')")) { 
      $('.section-icon').text('-'); 
     } 
     $(this).parent().next().toggle(); 
     $(this).siblings('.section-icon').toggleClass('open'); 
     return false; 
    }); 
});​ 

我的小提琴是這裏http://jsfiddle.net/6QW2K/

+7

「這根本不起作用。」不是錯誤消息,也不是問題描述。 – PeeHaa

+0

似乎你的小提琴缺少相當多的代碼。 – Scott

+0

您需要將您的html添加到小提琴中,以便我們瞭解您的問題... – jtheman

回答

1
if ($(".section-icon:contains('-')")) { 

始終計算爲true,您可以使用length屬性:

if ($(".section-icon:contains('-')").length) { 

http://jsfiddle.net/f2GZG/

您還可以使用text實現方法具ð而是採用:contains選擇:

$('.section-icon').text(function(i, cur){ 
    return cur === '+' ? '-' : '+' 
}) 

http://jsfiddle.net/UaGrt/

+0

感謝@undefined。我需要的只是length()方法。我很感激! – McGuyverr

+0

@McGuyverr不用客氣,請注意,我更改了選擇器,因爲它沒有在當前標記中選擇您的元素。 – undefined

+0

如果有超過1個「用戶電子郵件」類打印,它會按預期打印多個「+」號。點擊這些錨點後,它會更改所有列出的「+」和「 - 」符號。不知何故'$('。section-icon')。text('+');'需要使用其他方法,如parent(),siblings()或(this),但我不確定。你能幫我嗎? – McGuyverr