在HTML表单中使用自动生成的(即随机)的ID [英] Using auto generated (ie random) IDs in HTML forms
问题描述
我创建从我建为骨干的看法各种复杂的控制的一种形式。可以理解的是我想要的标签,以可靠地链接到<输入>
元素,我与正常做为
属性。
I'm creating a form from various complex controls that I have built as Backbone views. Understandably I want to reliably link the labels to the <input>
elements, which I am doing with the normal for
attribute.
不过,有时候我需要使用相同的控制多次。我使用的数据属性驱动的形式,所以我不需要 ID
属性为我所用,并且可以使用类来识别每个控制。
However, sometimes I need to use the same control multiple times. I am using data attributes to drive the form, so I do not need the id
attribute for my own use, and can use classes to identify each control.
所以,我正在考虑是否有意义,生成随机ID,只需链接&LT;标签&gt;
和&LT;输入&GT;
在一起吗?这似乎是一个非常糟糕的主意,但我不确定有一个更好的?
Therefore, I am considering whether it makes sense to generate random ids, just to link the <label>
and <input>
together? This seems a really bad idea, but I am unsure there is a better one?
我不能只是把&LT;输入&GT;
中的&LT;标签&gt;
,因为他们有是彼此独立的。
I can't just put the <input>
inside the <label>
, as they have to be separate from each other.
推荐答案
有什么坏的自动生成的ID。如果他们不被human-(==开发商)可读的,你可以去那里疯狂。创建一个简单的功能,即吐出独特的字符串,你去那里:
There's nothing bad in auto-generating IDs. If they have not to be human- (== developer) readable, you can go crazy there. Create a simple function, that spits out unique strings, and there you go:
function generateId() {
return 'GENERATED_ID_' + (++generateId.counter);
}
generateId.counter = 0;
id = generateId();
html = '<label for="'+id+'">Foo</label> <input id="'+id+'">';
没什么不好发生在这里。
Nothing bad happening here.
(当然,如果你的可能的窝在标签的投入,这将是一丁点更好。)
(Of course, if you could nest the input in the label, that would be a wee bit nicer.)
这篇关于在HTML表单中使用自动生成的(即随机)的ID的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!