2011-08-11 55 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。