在重复结构中检索DOM节点

时间:2013-06-13 10:54:54

标签: javascript jquery html dom

我正在编写一个库,在给定的DIV容器中构建一个复杂的HTML结构(使用JQuery)。

这是一个如何运作的例子:

HTML

<div id="a"></div>
<div id="b"></div>

LIBRARY JAVASCRIPT

function complexStructure(container, opts) {
    this._container = $(container);
    // code handling options
    // ...
}

complexStructure.prototype = {
    show: function () {
        this._buildStructure();
    },

    _buildStructure: function () {
        // building html nodes here
        // ...
        for ( x=0; ... ) {
            for ( y=0; ... ) {
                // ...
                obj.attr("id", this._idOfElement(x, y));
                // ...
            }
        }
        // ...      
        this._container.empty().append(structure);
    },

    _idOfElement: function (x ,y) {
        return "element_x_" + x + "_y_" + y;
    },

    updateElementState: function (x, y, state) {
            var element = this._container.find("#" + this._idOfElement(x, y));
            // ...
            // update element
            // ...
    }
};

LIBRARY USER JAVASCRIPT

var a = new complexStructure(document.getElementById("a"), {... opts ...});
var b = new complexStructure(document.getElementById("b"), {... opts ...});
a.show();
b.show();

在构建节点时,我为它们分配了ID,以便我以后可以检索它们。 要检索它们,我会从它们的祖先DIV容器中查找它们的ID,因为可能有多个具有相同ID的节点(在DIV a 和DIV b 中)。 / p>

我想知道在这种情况下是否可以使用重复ID,或者我是否应该使用CSS类或自定义属性。 在这种情况下,最佳做法是什么?您对整体架构的建议是什么?

当然,实际代码比这更复杂。

感谢您的时间

1 个答案:

答案 0 :(得分:0)

我要回答自己。

为避免ID重复,您只需将结构的每个节点的ID附加到其容器的ID。

一种解决方案是在构造函数或设置函数中为容器选择ID:

this._containerId = ... generate random/unique/sequential ID ...;

然后将元素的ID附加到其容器的ID:

_idOfElement: function (x, y) {
    return this._containerId + "_element_x_" + x + "_y_" + y;
}

如果您确定传递给构造函数的容器将始终插入到DOM树中(以便您可以使用getElementById检索它),另一种解决方案可能是从以下位置更改结构构造函数:

function complexStructure(container, opts) {
    this._container = $(container);
    // code handling options
    // ...
}

为:

function complexStructure(containerId, opts) {
    this._containerId = containerId;
    this._container = $("#" + containerId);
    // code handling options
    // ...
}

然后使用上面相同的_idOfElement函数。