简短问题: 如何使用jQuery和javascript将label元素链接到input元素而不使用input元素的id?
长问题: 我正在使用jQuery来克隆一个表单,可能有多个表单实例可供用户填写。
标签的'for'属性应该设置为输入元素的'id'属性。这在输入元素具有唯一ID时起作用。
因为我克隆了相同的输入元素,所以文档中将有多个具有相同id的输入元素。因此我避免使用输入元素的id属性,但是当单击标签时我还是要关注输入元素。我还想避免为字段生成随机ID或在标签上设置onclick事件。
编辑#1
示例标记(注意没有ID)
<form>
<label>First Name:</label><input type='text' name='FirstName' /><br/>
<label>Last Name:</label><input type='text' name='LastName' /><br/>
</form>
示例克隆代码:
var newForm = $('form').clone();
$(newForm).find('label').each(function(){
var inputElement = $(this).next('input');
// I'd love to set the label's for attribute to an element
$(this).attr('for', inputElement);
});
$(document).append(newForm);
编辑#2
目前有三种选择:
答案 0 :(得分:2)
很高兴看到标记,但如果我可以假设标记看起来有点像这样
<form name="f1">
<label>this is my label</label>
<input />
<label>this is my other label</label>
<input />
</form>
<form name="f2">
<label>this is my label</label>
<input />
<label>this is my other label</label>
<input />
</form>
然后你可以做这样的事情
$('form label').live('click',function(){
$(this).next('input').focus();
});
你需要使用live或delegate,因为你正在克服我正在假设的表格。
答案 1 :(得分:1)
最简单的解决方案是在<input>
标记内移动<label>
标记并完全放弃for
属性。根据HTML规范,没有<input>
属性的for
标记与其内容隐式关联。
试试这个:
<form>
<label>First Name: <input type='text' name='FirstName' /></label><br/>
<label>Last Name: <input type='text' name='LastName' /></label><br/>
</form>
(参见:http://www.w3.org/TR/html401/interact/forms.html#h-17.9.1)
答案 2 :(得分:0)
页面中不应有多个相同的ID。它违背了id属性的目的,并且是against the W3C spec。
无论如何,jQuery的$(this)
可以在这种情况下帮助你。说你给了你所有的“可聚焦”课程。然后你可以这样做:
$('.focusable').focus( function(){
$(this).doSomething();
});
答案 3 :(得分:0)
这实际上是一个HTML问题。标签可以通过其 for 属性与表单控件关联,该属性具有与关联控件的 id 属性相同的值,或者将控件作为标签的子级,例如
<form ...>
<label for="nameField">Name:<input id="nameField" name="nameField" ... ></label>
<label>email:<input name="emailField" ... ></label>
</form>
我想在jQuery中你需要类似的东西:
var labelAndInput = $('<label>text<input ... ></label>');
或其他什么。请注意,如果没有 for 属性(或 htmlFor 属性),旧版本的IE(也可能是更新版本的)标签将不会与控件关联,没有其他方式。