唯一html项ID在Javascript
-
05-07-2019 - |
题
我建立一个拖放gui建设者在Javascript。到目前为止一切顺利。
作为我的项目添加到图形用户界面和配置;我有两个机制处理这些问题:
- 该"类"-这是我的使用做事 所有实例 一个项目(例如CSS,通用功能等等),而我可以结合javascript库。我可以充分利用多晶型分类名称(即class="name1name2name3name4"与不同的事情开各类的名字...)
- 'id'-这是指 这个特别实例 文本框或一个段落,我可以结合javascript库
我的问题是这个:'id'必须是唯一的所有html项目在网页上(通过的定义),那么,如何确保这个吗?我需要得到所有身份证的所有项目,然后保持某种状态表。
从一个空白点html这是相当合理的-但是我需要开始从一个部分是创造点html与混合物的现有'id-其中一些将在我独特的方案和一些其不会是...
的方式来做到这最好的 应该 要解决的问题。
建议的技巧,例子吗?
解决方案
最好的方式做到这将完全依赖于的结构和组织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;
}
其他提示
function uniqueId() {
return 'id_' + new Date().getTime();
}
如果你碰巧是使用原型图书馆(或想要检查它的),可以使用的元素。确定()方法。
否则,他的反应是一个好主意。
function generateId() {
var chars = "0123456789abcdefghiklmnopqrstuvwxyz",
string_length = 8,
id = '';
for (var i = 0; i < string_length; i++) {
var rnum = Math.floor(Math.random() * chars.length);
id += chars.substring(rnum, rnum + 1);
}
return id;
}
足够接近的独特的足够好。不用的 Date()
解除非你是只产生一个单一的身份证在任何给定的时间...
不隶属于 StackOverflow