Javascript 或 Jquery 更改 onclick 类?

标签 javascript jquery click

当我单击时,我需要将类 .author 更改为 .authornew

我的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>

#showhide 是要按下的 id#author-dropdown 是下拉内容。现在,脚本更改了下拉内容的 id,但我实际上需要将类 .author 更改为 .authornew。我应该如何修改我的脚本来做到这一点?谢谢!

最佳答案

<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 的 author 类以及 author 类,然后将 authornew 类添加到对象中。

关于Javascript 或 Jquery 更改 onclick 类?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/7033769/

相关文章:

javascript - 如何告诉三个 Javascript 对象所有内容都已加载

jQuery - 从 jQuery 函数访问变量

html body gwt 点击事件

java - 单击 JTextField 中的图标并清除其内容

javascript - VBA 中的正则表达式 - 如何恢复搜索?

javascript - 是否可以使用 Javascript 关闭 Android 浏览器?

javascript - 如何使用 javascript 创建 Excel 文件?

javascript - 如何为移动设备制作固定的 div,但在单击时用滚动填充视口(viewport)

javascript - 单击登录建议时阻止 mouseLeave 事件

javascript - 单击按钮后向文本区域添加时间