如何从主jQuery对象中获取选择器信息?

时间:2018-03-16 16:56:48

标签: javascript jquery

很简单,我们有这条线。我想从以下网址获取信息:

console.log($('#fourth-step tr:nth-child(3) td:nth-child(3)'));

因此输出为#fourth-step tr:nth-child(3) td:nth-child(3)

这会输出一个非常长的对象,但我只需要选择器信息

我几乎肯定某个地方已经是关于这个问题的线索,但我找不到任何,抱歉。

为了方便起见,有一系列我尝试过的东西,但它们没有用。*

  1. console.log('z' + {obj});
  2. console.log(JSON.stringify({obj}));
  3. console.log(String({obj});
  4. {} - 快捷方式。

    有什么想法吗? :)

2 个答案:

答案 0 :(得分:0)

jQuery具有.selector()方法但不推荐使用,因为它不会返回 - 有时 - 返回所需的结果。试试这个我编写的jQuery插件,以获得更独特的CSS选择器:



$.fn.extend({
  getSelector: function() {
    var path = [],
      currentElement = this[0];

    while (currentElement.nodeName.toLowerCase() != 'html') {
      var selector = currentElement.nodeName.toLowerCase();

      if (currentElement.id)
        selector += '#' + currentElement.id;

      if (!currentElement.id && currentElement.className)
        selector += '.' + currentElement.className;

      path.push(selector);

      currentElement = currentElement.parentNode;
    }

    return path.reverse().join(' > ');
  }
});




查看这个git repo:jQuery Plugins Library

答案 1 :(得分:0)

在jQuery 1.7之前,有selector属性,但它现在已被弃用。您可以做的最好的事情是将选择器存储为元素的属性,如下所示:

$(selector).data('selector',selector)

请注意,在页面中移动或克隆元素后,选择器可能不再匹配元素。这可能是selector属性弃用的原因。

另见here