如何在INPUT标记上没有ID属性的情况下使用LABEL标记的FOR属性

时间:2022-11-25 19:24:38

Is there a solution to the problem illustrated in the code below? Start by opening the code in a browser to get straight to the point and not have to look through all that code before knowing what you're looking for.

是否有解决下面代码中说明的问题的方法?首先在浏览器中打开代码直接到达关键点,而不必在知道您要查找的内容之前查看所有代码。

<html>
 <head>
  <title>Input ID creates problems</title>
  <style type="text/css">
   #prologue, #summary { margin: 5em; }
  </style>
 </head>
 <body>
  <h1>Input ID creates a bug</h1>
  <p id="prologue">
   In this example, I make a list of checkboxes representing things which could appear in a book. If you want some in your book, you check them:
  </p>
  <form>
   <ul>
    <li>
     <input type="checkbox" id="prologue" />
     <label for="prologue">prologue</label>
    </li>
    <li>
     <input type="checkbox" id="chapter" />
     <label for="chapter">chapter</label>
    </li>
    <li>
     <input type="checkbox" id="summary" />
     <label for="summary">summary</label>
    </li>
    <li>
     <input type="checkbox" id="etc" />
     <label for="etc">etc</label>
     <label>
    </li>
   </ul>
  </form>
  <p id="summary">
   For each checkbox, I want to assign an ID so that clicking a label checks the corresponding checkbox. The problems occur when other elements in the page already use those IDs. In this case, a CSS declaration was made to add margins to the two paragraphs which IDs are "prologue" and "summary", but because of the IDs given to the checkboxes, the checkboxes named "prologue" and "summary" are also affected by this declaration. The following links simply call a javascript function which writes out the element whose id is <a href="javascript:alert(document.getElementById('prologue'));">prologue</a> and <a href="javascript:alert(document.getElementById('summary'));">summary</a>, respectively. In the first case (prologue), the script writes out [object HTMLParagraphElement], because the first element found with id "prologue" is a paragraph. But in the second case (summary), the script writes out [object HTMLInputElement] because the first element found with id "summary" is an input. In the case of another script, the consequences of this mix up could have been much more dramatic. Now try clicking on the label prologue in the list above. It does not check the checkbox as clicking on any other label. This is because it finds the paragraph whose ID is also "prologue" and tries to check that instead. By the way, if there were another checkbox whose id was "prologue", then clicking on the label would check the one which appears first in the code.
  </p>
  <p>
   An easy fix for this would be to chose other IDs for the checkboxes, but this doesn't apply if these IDs are given dynamically, by a php script for example.
   Another easy fix for this would be to write labels like this:
   <pre>
    &lt;label&gt;&lt;input type="checkbox" /&gt;prologue&lt;/label&gt;
   </pre>
   and not need to give an ID to the checkboxes. But this only works if the label and checkbox are next to each other.
  </p>
  <p>
   Well, that's the problem. I guess the ideal solution would be to link a label to a checkboxe using another mechanism (not using ID). I think the perfect way to do this would be to match a label to the input element whose NAME (not ID) is the same as the label's FOR attribute. What do you think?
  </p>
 </body>
</html>

5 个解决方案

#1


13  

The best, to my mind, what you can do, is to rename all the checkboxes, by adding some prefix to their ids, for example input

在我看来,你能做的最好的事情就是重命名所有的复选框,在它们的id中添加一些前缀,例如输入

   <ul>
    <li>
     <input type="checkbox" id="input_prologue" />
     <label for="input_prologue">prologue</label>
    </li>
    <li>
     <input type="checkbox" id="input_chapter" />
     <label for="input_chapter">chapter</label>
    </li>
    <li>
     <input type="checkbox" id="input_summary" />
     <label for="input_summary">summary</label>
    </li>
    <li>
     <input type="checkbox" id="input_etc" />
     <label for="input_etc">etc</label>
    </li>
   </ul>

This way you will not have any conflicts with other ids on a page, and clicking the label will toggle the checkbox without any special javascript function.

这样,您就不会与页面上的其他ID发生冲突,单击标签将切换复选框,而不需要任何特殊的javascript函数。

#2


107  

it's been resolved here: https://*.com/a/8537641 just do it like this

它在这里得到了解决:https://*.com/a/8537641就这样做了

<label><input type="checkbox">Some text</label>

#3


6  

EDIT: In retrospect, my solution is far from ideal. I recommend that you instead leverage "implicit label association" as shown in this answer: *.com/a/8537641/884734

编辑:回想起来,我的解决方案远非理想。我建议您改为利用“隐式标签关联”,如下所示:*.com/a/8537641/884734

My proposed, less-than-ideal solution is below:

我提出的不太理想的解决方案如下:

This problem can be easily solved with a little javascript. Just throw the following code in one of your page's js files to give <label> tags the following behavior:

用一点点javascript就可以轻松解决这个问题。只需将以下代码放入页面的一个js文件中,即可为

When a label is clicked:

单击标签时:

If there is an element on the page with an id matching the label's for attribute, revert to default functionality and focus that input.

如果页面上的元素的id与标签的属性匹配,则还原为默认功能并关注该输入。

If no match was found using id, look for a sibling of the label with a class matching the label's for attribute, and focus it.

如果找不到使用id的匹配项,请查找标签的兄弟,并使用与属性的标签匹配的类,并将其聚焦。

This means that you can lay out your forms like this:

这意味着您可以像这样布置表单:

<form>
    <label for="login-validation-form-email">Email Address:</label>
    <input type="text" class="login-validation-form-email" />
</form>

Alas, the actual code:

唉,实际代码:

$(function(){
    $('body').on('click', 'label', function(e){
        var labelFor = $( this ).attr('for');
        if( !document.getElementById(labelFor) ){
            e.preventDefault(); e.stopPropagation();
            var input = $( this ).siblings('.'+labelFor);
            if( input )
                input[0].focus();
        }
    })
});

Note: This may cause issues when validating your site against the W3C spec, since the <label> for attribute is supposed to always have a corresponding element on the page with a matching ID.

注意:根据W3C规范验证站点时,这可能会导致问题,因为

Hope this helps!

希望这可以帮助!

#4


2  

Simply put, an ID is only supposed to be used once on a page, so no they wouldn't design a workaround for multiple ID's on a single page which aren't supposed to exist.

简单地说,ID只应该在页面上使用一次,因此不会为单个页面上的多个ID设计一个不应该存在的变通方法。

To answer the rest of the question: no, the ID attribute is the only thing a label's 'for' attribute will look at. You can always use a JavaScript onclick event to fetch the input by name and change it, though that seems overly complicated when you can just fix your ID issue, which would make a lot more sense.

要回答问题的其余部分:不,ID属性是标签'for'属性的唯一内容。您总是可以使用JavaScript onclick事件来按名称获取输入并进行更改,但是当您可以修复ID问题时这似乎过于复杂,这会更有意义。

#5


0  

Maybe easy straightforward solution would be using uniqueid() php or other programming language alternative function.

也许简单直接的解决方案是使用uniqueid()php或其他编程语言替代功能。

#1


13  

The best, to my mind, what you can do, is to rename all the checkboxes, by adding some prefix to their ids, for example input

在我看来,你能做的最好的事情就是重命名所有的复选框,在它们的id中添加一些前缀,例如输入

   <ul>
    <li>
     <input type="checkbox" id="input_prologue" />
     <label for="input_prologue">prologue</label>
    </li>
    <li>
     <input type="checkbox" id="input_chapter" />
     <label for="input_chapter">chapter</label>
    </li>
    <li>
     <input type="checkbox" id="input_summary" />
     <label for="input_summary">summary</label>
    </li>
    <li>
     <input type="checkbox" id="input_etc" />
     <label for="input_etc">etc</label>
    </li>
   </ul>

This way you will not have any conflicts with other ids on a page, and clicking the label will toggle the checkbox without any special javascript function.

这样,您就不会与页面上的其他ID发生冲突,单击标签将切换复选框,而不需要任何特殊的javascript函数。

#2


107  

it's been resolved here: https://*.com/a/8537641 just do it like this

它在这里得到了解决:https://*.com/a/8537641就这样做了

<label><input type="checkbox">Some text</label>

#3


6  

EDIT: In retrospect, my solution is far from ideal. I recommend that you instead leverage "implicit label association" as shown in this answer: *.com/a/8537641/884734

编辑:回想起来,我的解决方案远非理想。我建议您改为利用“隐式标签关联”,如下所示:*.com/a/8537641/884734

My proposed, less-than-ideal solution is below:

我提出的不太理想的解决方案如下:

This problem can be easily solved with a little javascript. Just throw the following code in one of your page's js files to give <label> tags the following behavior:

用一点点javascript就可以轻松解决这个问题。只需将以下代码放入页面的一个js文件中,即可为

When a label is clicked:

单击标签时:

If there is an element on the page with an id matching the label's for attribute, revert to default functionality and focus that input.

如果页面上的元素的id与标签的属性匹配,则还原为默认功能并关注该输入。

If no match was found using id, look for a sibling of the label with a class matching the label's for attribute, and focus it.

如果找不到使用id的匹配项,请查找标签的兄弟,并使用与属性的标签匹配的类,并将其聚焦。

This means that you can lay out your forms like this:

这意味着您可以像这样布置表单:

<form>
    <label for="login-validation-form-email">Email Address:</label>
    <input type="text" class="login-validation-form-email" />
</form>

Alas, the actual code:

唉,实际代码:

$(function(){
    $('body').on('click', 'label', function(e){
        var labelFor = $( this ).attr('for');
        if( !document.getElementById(labelFor) ){
            e.preventDefault(); e.stopPropagation();
            var input = $( this ).siblings('.'+labelFor);
            if( input )
                input[0].focus();
        }
    })
});

Note: This may cause issues when validating your site against the W3C spec, since the <label> for attribute is supposed to always have a corresponding element on the page with a matching ID.

注意:根据W3C规范验证站点时,这可能会导致问题,因为

Hope this helps!

希望这可以帮助!

#4


2  

Simply put, an ID is only supposed to be used once on a page, so no they wouldn't design a workaround for multiple ID's on a single page which aren't supposed to exist.

简单地说,ID只应该在页面上使用一次,因此不会为单个页面上的多个ID设计一个不应该存在的变通方法。

To answer the rest of the question: no, the ID attribute is the only thing a label's 'for' attribute will look at. You can always use a JavaScript onclick event to fetch the input by name and change it, though that seems overly complicated when you can just fix your ID issue, which would make a lot more sense.

要回答问题的其余部分:不,ID属性是标签'for'属性的唯一内容。您总是可以使用JavaScript onclick事件来按名称获取输入并进行更改,但是当您可以修复ID问题时这似乎过于复杂,这会更有意义。

#5


0  

Maybe easy straightforward solution would be using uniqueid() php or other programming language alternative function.

也许简单直接的解决方案是使用uniqueid()php或其他编程语言替代功能。