【问题标题】:Using this with pseudo selectors jquery将其与伪选择器 jquery 一起使用
【发布时间】:2015-02-04 09:01:22
【问题描述】:

我想知道是否有办法在 jQuery 中将 this 与 CSS 伪选择器(也称为嵌套元素)一起使用。这可能是它的样子。

    $('#element').click(function(){
        $(this' .nested').css('height','100px');
    });

但这不是语法的工作方式。我只是想知道它是如何工作的。

【问题讨论】:

    标签: javascript jquery css this pseudo-class


    【解决方案1】:

    请改用find()。示例:

    $('#element').click(function(){
        $(this).find('.nested').css('height','100px');
    });
    

    【讨论】:

    • 谢谢一百万。这是完美的。
    【解决方案2】:

    当你使用 $(this) 使用 .find() 来获取你想要的元素 像这样

    $('#element').click(function(){    
       $(this).find('.nested').css('height','100px');
    });
    

    【讨论】:

      【解决方案3】:

      您可以使用 .css() 或者也可以在 jQuery 中切换一个类并在您的 CSS 文件中设置 CSS 属性,这通常具有更高的性能和可重用性。

      $('#element').click(function(){    
         $(this).find('.nested').css('height','100px');
      });
      

      也可以

      $('#element').click(function(){    
         $(this).find('.nested').toggleClass('height-nested');
      });
      

      CSS

      .height-nested{
         height: 100px;
      }
      

      【讨论】:

        【解决方案4】:

        使用以下代码

        $('#element').click(function(){
            $('.nested',this).css('height','100px');
        });
        

        或者

        $('#element').click(function(){
            $(this).find('.nested').css('height','100px');
        });
        

        【讨论】:

        猜你喜欢
        • 2021-09-01
        • 1970-01-01
        • 1970-01-01
        • 2021-12-09
        • 1970-01-01
        • 1970-01-01
        • 2011-11-01
        • 1970-01-01
        • 2012-03-07
        相关资源
        最近更新 更多