Javascript疯狂的想法找到一个节点 [英] Javascript crazy idea finding a node

查看:87
本文介绍了Javascript疯狂的想法找到一个节点的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个疯狂(但很疯狂,它可能工作)想法,一个页面上的每个元素都是在javascript中创建的,但给出了一个ID,它是DOM中的路径的哈希。

I had a crazy (but so crazy that it just might work) idea where every element on a page is created in javascript but given an ID which is a hash of its path in the DOM.

所以,不是通过DOM搜索一个元素,而是将路径哈希,然后将 getElementById()那个哈希。

So instead of searching through the DOM to find an element, you hash the path and then getElementById() with that hash.

这个问题是获得路径可能比首先搜索DOM要贵一些。任何想法可以如何做,或者只是简单的愚蠢?

Problem with this is getting the path might be more expensive than searching the DOM in the first place. Any ideas how this could be done or if it is just plain stupid?

推荐答案

如果你知道元素的完整路径,要走这条路真的很难够证明这种事情吗?通常情况下,通过与绝对路径无关的常见方面来收集元素,这是一个麻烦。而在那里,像 Sizzle 这样的引擎,我不知道我看到了这个用例。 : - )

If you know the full path of the element, is going to that path actually hard enough to justify this sort of thing? Usually it's things like collecting elements by common aspects unrelated to their absolute path that's a hassle. And with engines like Sizzle out there, I'm not sure I'm seeing the use-case for this. :-)

我也想知道如何在移动元素时处理它。重新分配哈希,可能是开始变得丑陋。

I also wonder how you would handle it when moving elements around. Re-assign their hashes, presumably, which starts getting ugly fast.

请注意,您的方法不仅仅是使用运行时创建的元素通过Javascript;您可以使用递归下降函数轻松地分配这些事实:

Note that your approach doesn't only work with elements created at runtime by Javascript; you can assign them after the fact easily enough with a recursive descent function:

function createIDs(element) {
    var child;

    if (!element.id) {
        element.id = createElementID(element);
    }
    for (child = element.firstChild; child; child = child.nextSibling) {
        if (child.nodeType == 1) { // Element
            createIDs(child);
        }
    }
}

// Kick things off
createIDs(document.body);

这是对预生成内容的一次性打击,而不是总是必须重新生成内容。不提倡,只是指出。

That's a one-time hit on pre-generated content, rather than always having to re-generate content. Not advocating, just pointing out.

这篇关于Javascript疯狂的想法找到一个节点的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆