设置标签's表示DOM元素的属性,而不是jQuery中的ID

Setting a label's for attribute to a DOM element, not an ID in jQuery

本文关键字:属性 ID 中的 jQuery 元素 标签 DOM 表示 设置      更新时间:2023-09-26

简短问题:如何使用jQuery和javascript将标签元素链接到输入元素,而不使用输入元素的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

目前有三种选择:

  • 为标签设置onclick事件,使其专注于它们所针对的输入字段。决定哪些标签用于哪些输入可以是下一个输入元素或其他内容的标准
  • 在标签字段中嵌入输入字段(可能由于设计者的选择而无法实现)
  • 克隆每个表单时生成随机ID

很高兴看到标记,但如果我可以假设标记看起来有点像这个

<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,因为我假设您正在动态克隆表单。

最简单的解决方案是将<input>标记移到<label>标记内,并完全放弃for属性。根据HTML规范,没有for属性的<input>标记与其内容隐式关联。

试试这个:

<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)

页面中不应该有多个相同的id。它违背了id属性的目的,违反了W3C规范

无论如何,jQuery的$(this)可以在这种情况下为您提供帮助。假设你上了所有"可聚焦"的课。然后你可以做:

$('.focusable').focus( function(){
     $(this).doSomething(); 
});

这实际上是一个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(可能还有更新版本)标签将不会与控件关联,没有其他方法。