虽然我从来没有听说过这一点,但是,是否可以使用JS从DOM中检索节点,然后找出该节点出现在文件的哪一行?
我对任何东西都是开放的,其他的浏览器插件/附加组件etc...it不需要是跨浏览器的。
考虑到一些JS调试器能够找到script标记中的行号,我假设这是可能的,但我不能完全确定。
发布于 2010-01-12 04:31:25
这是可以做到的。首先获取文档中最高的节点,如下所示:
var htmlNode = document.getElementsByTagName('html')[0];
var node = htmlNode;
while (node.previousSibling !== null) {
node = node.previousSibling;
}
var firstNode = node;
(测试并检索了doctype节点和html节点上的注释)
然后遍历所有节点(包括同级节点和子节点)。在IE中,你只能看到元素和注释(而不是文本节点),所以最好使用FF或chrome或其他东西(你说过它不必是跨浏览器的)。
当您到达每个text node时,解析它以查找回车。
发布于 2010-01-12 04:36:02
像这样的东西?
var wholeDocument = document.getElementsByTagName('html')[0]
var findNode = document.getElementById('whatever')
var documentUpToFindNode = wholeDocument.substr(0, wholeDocument.indexOf(findNode.outerHTML))
var nlsUpToFindNode = documentUpToFindNode.match(/\n/g).length
发布于 2010-01-12 11:45:35
你可以试试:
- start at the 'whatever' node,
- traverse to each previous node back to the doc begining while concatenating the html of each node,
- then count the new lines in your collected HTML.
把代码写出来,因为这是一个很好的问题:)
https://stackoverflow.com/questions/2044642
复制相似问题