【问题标题】:JQuery: add class to element - cannot use this class for selector?JQuery:向元素添加类 - 不能将此类用于选择器?
【发布时间】:2012-08-30 17:15:28
【问题描述】:

我有以下问题:为了在不同情况下标记元素,我想为元素添加一个类:

jQuery('#menu-item-41 a').addClass('newsbox-closed1');

稍后,当单击具有此类的元素时,我想做一些有趣的工作人员-到目前为止,它工作正常:

jQuery('.newsbox-closed1').click(function(){
      jQuery('#newsbox').css('display', 'block');
      jQuery(this).css('background-color', '#FF33AB').removeClass('newsbox-closed1').addClass('news-open');
 });

到目前为止,一切都很好。元素获得类“news-open”并且新闻框出现。但随后以下内容不再起作用:

jQuery('.news-open').click(function(){
  alert('JUCVJU');
  jQuery(this).removeClass('news-open').addClass('newsbox-closed2');
  jQuery('#newsbox').css('display', 'none');
});

想法:当有人再次点击同一个链接时,新闻框应该会消失并且链接会得到一个新的类。这不起作用 - 没有删除类“new-open”,没有显示警报框,什么都没有。 此外,以下工作只完成了一半 - 它是新闻框上的关闭按钮:

jQuery('#close').click(function(){
  jQuery('#newsbox').css('display', 'none');
  jQuery('.news-open').removeClass('news-offen').addClass('newsbox-closed2')
});

id 为“newsbox”的元素消失了,但第二部分没有效果。该元素的类仍然存在。我没有收到任何错误消息,什么都没有……有人知道是什么原因造成的吗?

最好, 托比亚斯

【问题讨论】:

  • 把它放在 jsFiddle 中会有很大帮助

标签: jquery jquery-selectors addclass


【解决方案1】:

您正在运行时添加类。改变

jQuery('.news-open').click(function(){

到

jQuery('.news-open').on('click',(function(){

以上适用于 JQuery >=1.7

对于 JQuery

jQuery('.news-open').live('click',function(){

在运行时创建的元素也可以在 JQuery 中使用。

【讨论】:

    【解决方案2】:

    您可能需要委派您的事件处理程序,因为您要在文档加载后更改类。换个试试

    jQuery('.news-open').click(function(){
    

    与

    jQuery(document).on('click', '.news-open', function(){
    

    不过,如果您可以使它比 document 更具体,那么您应该这样做。将您的活动委托给最近的 .news-open 容器,以实现最佳效率。

    http://api.jquery.com/on/

    【讨论】:

      【解决方案3】:

      谢谢大家!!!

      为了让其他面临类似问题的人明白这一点,我的工作代码如下所示:

      jQuery('#menu-item-41').on('click', '.news-open', (function(){
        alert('JUCVJU');
        jQuery(this).removeClass('news-open').addClass('newsbox-closed2');
        jQuery('#newsbox').css('display', 'none');
      }));
      

      id“menu-item-41”是容器的id,它围绕着我的元素,类为“news-open”。现在,当我再次单击进一步重新分类的元素并且新闻框消失时,我会看到警报框。

      【讨论】:

        【解决方案4】:

        非常相似的问题:在单击链接时,我制作了一个动画来显示隐藏的 div,并将 '.hideMe' 类添加到布局的其余部分,以便单击显示的 div 之外的任意位置将再次隐藏它。 '.hideMe' 不能被 jQuery 选择,因为它在页面加载时不存在。通过将两个 .on() 方法与委托链接在一起来解决,如下所示:https://stackoverflow.com/a/8261148

        $(document.body).on('click', '#link', function() {
          $('div').addClass('.hideMe').animate(); // animation code here
          $('#newdiv').show();
        }).on('click', '.hideme', function() {
          $('div').removeClass('.hideMe').animate(); // animation code here
          $('#newdiv').hide();
        });
        

        这是 jQuery 1.10.x。

        【讨论】:

          猜你喜欢
          • 1970-01-01
          • 2012-07-26
          • 2015-03-15
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 2016-05-05
          • 2023-03-09
          相关资源
          最近更新 更多