0

我有一个返回我 html 路径的小函数

getDomPath = function(el) {
  var count, element, path, selector;
  count = void 0;
  element = void 0;
  path = void 0;
  selector = void 0;
  element = el;
  if (!(el instanceof Element)) {
    return;
  }
  path = [];
  while (el.nodeType === Node.ELEMENT_NODE && el.id !== "jobs") {
    selector = el.nodeName.toLowerCase();
    if (el.id) {
      selector += "#" + el.id;
    } else if (el.className) {
      selector += "." + el.className;
    } else {
      count = $(el).prevAll().length + 1;
      selector += ":nth-child(" + count + ")";
    }
    path.unshift(selector);
    el = el.parentNode;
  }
  return path.join(" > ");
};

它运作良好,但有时我的代码标签中有<style>or <title>。我如何在我的 javascript 函数中跳过这个标签,所以它不会将它们计入我的第 n 个孩子?

例如。我有以下代码

<table>
<sometag></sometag>
<tr>
<p>My paragraph here</p>
<tr>
</table>

所以作为这个功能的结果,我想成为

table:nth-child(1) > tr:nth-child(1) > p:nth-child(1)

但相反我会得到

table:nth-child(1) > tr:nth-child(2) > p:nth-child(1)

因为脚本计算所有先前的元素

4

1 回答 1

0

感谢@JasonP,他说我可以按照以下方式做 count = $(el).prevAll(':not(sometag)').length + 1;

于 2013-11-06T08:54:15.260 回答