【问题标题】:Retrieve the string representation of a jQuery selector检索 jQuery 选择器的字符串表示
【发布时间】:2011-09-08 15:28:30
【问题描述】:

将给定的 jQuery 选择器 $('#my-id .my-class a') 存储为变量 jqElement,我如何返回该选择器的字符串表示形式?

换句话说:

jqElement = $('#my-id .my-class a');
jqElement.someFunc(); // returns '#my-id .my-class a'

我在这里查看How do I get a jQuery selector's expression as text?,但发现信息已过时且可能不完整。

【问题讨论】:

标签: jquery string selector


【解决方案1】:

正如您链接到的问题的答案中所提供的,selector 属性是您能找到的最合适的方法。

虽然对于基本选择器来说它是完全准确的,但您会发现,当使用 parent()next() 等操作方法时,.selector 属性将变得无法重用:

alert($('foo[id^=fish]:gt(5):eq(4)').selector); // foo[id^=fish]:gt(5):eq(4)
alert($('foo').children('bar').next().selector); // foo.children(bar).next()

例如您可以将第一个直接插入$(),但不能插入后者。

【讨论】:

    【解决方案2】:
    $('#my-id .my-class a').selector;
    

    【讨论】:

      【解决方案3】:
      jqElement.selector
      

      将返回选择器值

      【讨论】:

        【解决方案4】:

        selector 属性公开了一个 jQuery 对象的选择器。比如……

        var cache = $("#my-id .my-class a");
        
        alert(cache.selector); // will alert "#my-id .my-class a"
        

        【讨论】:

          猜你喜欢
          • 1970-01-01
          • 2018-07-14
          • 1970-01-01
          • 1970-01-01
          • 2011-01-25
          • 2011-01-13
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          相关资源
          最近更新 更多