これを行う最善の方法は、JavaScript の構造と構成に完全に依存します。 オブジェクトを使用して各 GUI 要素を表していると仮定すると、静的カウンターを使用して ID をインクリメントできます。
// Your element constructor
function GuiElement() {
this.id = GuiElement.getID();
}
GuiElement.counter = 0;
GuiElement.getID = function() { return 'element_' + GuiElement.counter++; };
もちろん、おそらく複数のタイプの要素を持っているので、それぞれに独自のカウンター (例: form_1、form_2、label_1、label_2) を持つように設定するか、すべての要素がカウンターを共有するように (例: element_1、 element_2、element_3) ですが、どちらの方法でも、おそらくいくつかの基本オブジェクトから継承する必要があります。
// Your base element constructor
function GuiElement(tagName, className) {
this.tagName = tagName;
this.className = className;
}
GuiElement.counter = 0;
GuiElement.getID = function() { return 'element_' + GuiElement.counter++; };
GuiElement.prototype.init = function() {
this.node = document.createElement(this.tagName);
this.node.id = this.id = GuiElement.getID();
this.node.className = this.className;
}
// An element constructor
function Form() {
this.init();
}
Form.prototype = new GuiElement('form', 'form gui-element');
// Another element constructor
function Paragraph() {
this.init();
}
Paragraph.prototype = new GuiElement('p', 'paragraph gui-element');
一部の変数を「プライベート」に保ちたい場合は、次の方法も使用できます。
// Your element constructor constructor
var GuiElement = (function() {
var counter = 0;
function getID() {
return 'element_' + counter++;
}
return function GuiElement(tagName, className) {
return function() {
this.node = document.createElement(tagName);
this.node.id = this.id = getID();
this.node.className = className + ' gui-element';
this.className = className;
};
}
})();
// Create your element constructors
var Form = GuiElement('form', 'form'),
Paragraph = GuiElement('p', 'paragraph');
// Instantiate elements
var f1 = new Form(),
f2 = new Form(),
p1 = new Paragraph();
更新: ID がまだ使用されていないことを確認する必要がある場合は、getID メソッドのチェックを追加できます。
var counter = 0;
function getID() {
var id = 'element_' + counter++;
while(document.getElementById(id)) id = 'element_' + counter++;
return id;
}