2011-08-11 53 views
0

我點擊時需要將類別.author更改爲.authornewJavascript或jquery更改類onclick?

我的html:

<div class="meta-info" id="showhide"> 
    <div class="author"></div> 
<div id="author-dropdown" style="display: none;"></div>  

我的腳本:

<script> 
$(document).ready(function() { 
    $('#showhide').click(function() { 
    if($('#author-dropdown').css('display') == 'none') { 
     $('#author-dropdown').attr("id","author-dropdown-extended").slideDown(); 
    } else { 
     $('#author-dropdown-extended').attr("id","author-dropdown").slideUp(); 
    } 
    return false; 
    }); 
}); 
</script> 

#showhideid按上。 #author-dropdown是下拉內容。現在,腳本更改了下拉內容的id,但實際上我需要將類.author更改爲.authornew。我應該如何修改我的腳本來做到這一點?謝謝!

回答

6
<script> 
    $(document).ready(function() { 
     $('div#showhide').click(function() { 

      //Check if element with class 'author' exists, if so change it to 'authornew' 
      if ($('div.author').length != 0) 
       $('div.author').removeClass('author').addClass('authornew'); 
      //Check if element with class 'authornew' exists, if so change it to 'author' 
      else if ($('div.authornew').length != 0) 
       $('div.authornew').removeClass('authornew').addClass('author'); 

     }); 
    }); 
</script> 

這應該做的伎倆!

首先,它消除了筆者類的DIV的帶班作者,它然後添加類authornew對象。

+0

它改變了班級,但它不會返回到前一班,只需點擊一下。 – funguy

+0

對不起,我不知道你想要那個。相應地編輯我的答案。 – Jules

+0

它有幫助。涼! – funguy

1

您可以使用addClassremoveClass jQuery方法:

$('.author').removeClass('author').addClass('authornew'); 
+0

而且,它改變了類,但它不回到以前的類,在第二次點擊。 – funguy

2

更新的解決方案:

如果你只是想從.author.author類切換到.authornew和回.authorclick()事件,那麼你就應該能夠利用toggle()功能:

HTML :

<div class="meta-info" id="showhide">  
    <div class="author">1</div> 
    <div id="author-dropdown" style="display: none;"> 
</div> 

CSS:

.author { background: #000; } 
.authornew { background: #ccc; } 

jQuery的:與toggle()

$('#showhide').click(function() { 
    $('div.author').toggleClass('authornew'); 
}); 

工作例如:http://jsfiddle.net/zydJd/

一個簡單的條件的例子是:

var obj = $(this); 
if(obj.hasClass('author')){ 
    obj.removeClass('author').addClass('authornew'); 
}else{ 
    obj.removeClass('authornew').addClass('author'); 
} 

其中$(這)會引用對象的問題,即$('.author')

或者只作則變化:

$('.author').removeClass('author').addClass('authornew'); 
+0

它會更改類,但不會返回到上一個類,只需單擊第二次。 – funguy

+0

不知道你需要切換類。更新解決方案 – RobB

1

jQuery的toggleClass可能是有用的了。

$('#author-dropdown').toggleClass("author authornew"); 

這會在您每次調用它時切換作者和authornew之間的類。它的工作原理是刪除存在的並添加不存在的。如果最初存在,那麼每次調用它時都會在兩者之間切換。

在內部,jQuery對傳入的類名進行字符串拆分以隔離每個名稱,然後對於每個傳遞的className,它會對其執行hasClass,如果爲true,則執行removeClass,如果不是true,則執行addClass。