无法弄清楚使用 jquery 添加/删除类

Can't figure out adding/removing classes with jquery

本文关键字:添加 删除 jquery 弄清楚      更新时间:2023-09-26

我需要有关我的wordpress主题的JS代码的帮助。第一部分是当它查找 h4 标题时,如果它有某些文本,它会将此 h4 下的所有段落包装为div(将所有段落隐藏到淡入淡出部分)并添加"按钮"(即跨度):

var tutustu = 'TUTUSTU'; 
    var syvenny = 'SYVENNY';
    $('.article_content h4').each(function(){
        if($(this).text() == tutustu)
        {
            $(this).nextUntil("h4").wrapAll('<div class="expand" />').parent().append('<span id="expand">show more</span>');
        }
        else if($(this).text() == syvenny) {
            $(this).nextUntil("h4").wrapAll('<div class="expand" />').parent().append('<span id="expand">show more</span>');
        }
    });

其次是当用户单击"按钮"div(我们提前包装到所有段落中)将获得另一个类(基本上显示所有段落)和删除按钮:

$('span#expand').click(function() {
  $(this).parent('.expand').removeClass('expand').addClass('expanded');
  $(this).remove();
});

我需要的是,在显示段落文本后,我想点击按钮,一切都像第一部分一样返回。我想出了这样的东西:

$('span#expanded').click(function() {
  $(this).parent('.expanded').removeClass('expanded').addClass('expand');
});

但它不起作用(非常感谢帮助

使用 event Delegation.toggleClass() 而不是 .addClass().removeClass()

$(document).on("click" , "span#expanded" , function() {
  $(this).parent().toggleClass('expanded expand');
});
 $('#expanded').on('click', function(e) {
   $(this).parent().toggleClass('expanded expand');
   e.preventDefault();
  });