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

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/2703356/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-29 02:49:53  来源:igfitidea点击:

How can I use the FOR attribute of a LABEL tag without the ID attribute on the INPUT tag

htmlinputlabelfor-loop

提问by Shawn

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>

采纳答案by Draco Ater

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 中添加一些前缀 input

   <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 功能。

回答by user2046841

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

它已在这里解决:https: //stackoverflow.com/a/8537641就这样做

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

回答by Eric Seastrand

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

编辑:回想起来,我的解决方案远非理想。我建议您改用“隐式标签关联”,如本答案所示:stackoverflow.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 文件之一中抛出以下代码,即可为<label>标签提供以下行为:

When a label is clicked:

单击标签时:

If there is an element on the page with an idmatching the label's forattribute, revert to default functionality and focus that input.

如果页面上有id与标签for属性匹配的元素,则恢复为默认功能并聚焦该输入。

If no match was found using id, look for a sibling of the labelwith a classmatching the label's forattribute, and focus it.

如果使用未找到匹配id,寻找的兄弟姐妹label有一个class匹配labelfor属性,并将重点。

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>forattribute is supposed to always have a corresponding element on the page with a matching ID.

注意:当根据 W3C 规范验证您的站点时,这可能会导致问题,因为该<label>for属性应该始终在页面上具有匹配 ID 的相应元素。

Hope this helps!

希望这可以帮助!

回答by animuson

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 问题时,这似乎过于复杂,这会更有意义。

回答by FentomX1

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

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

回答by yancheelo

Unlike the accepted answer, I agree with the solution proposed by FantomX1, generate a random id for every checkbox and use this id for the label associated to the checkbox. But I would generate the random id using a uuid (see Create GUID / UUID in JavaScript?)

与接受的答案不同,我同意 FantomX1 提出的解决方案,为每个复选框生成一个随机 id,并将此 id 用于与复选框关联的标签。但我会使用 uuid 生成随机 ID(请参阅在 JavaScript 中创建 GUID/UUID?