【问题标题】:How can I use the FOR attribute of a LABEL tag without the ID attribute on the INPUT tag如何在 INPUT 标签上没有 ID 属性的情况下使用 LABEL 标签的 FOR 属性
【发布时间】:2011-02-11 19:12:03
【问题描述】:

下面代码中说明的问题是否有解决方案?首先在浏览器中打开代码直奔主题,而无需查看所有代码即可知道您要查找的内容。

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

【问题讨论】:

标签: html input label for-loop


【解决方案1】:

简单地说,一个 ID 只能在一个页面上使用一次,所以他们不会为单个页面上不应该存在的多个 ID 设计解决方法。

回答剩下的问题:不,ID 属性是标签的“for”属性将查看的唯一内容。您始终可以使用 JavaScript onclick 事件按名称获取输入并更改它,尽管当您可以修复您的 ID 问题时,这似乎过于复杂,这会更有意义。

【讨论】:

  • +1 表示用一块石头解决两个问题。一些毫无意义的仅供参考:for 属性是数据类型 IDREF,它查看类型 ID 的值,该值必须是唯一的。这些是 XML Schema 可用的遗留数据类型,所以我想这意味着它们是 SGML 的常驻数据类型。
  • 动态创建输入的 id 时会出现问题。当我为页面上的其他元素选择 ID 时,我无法知道它们会是什么,因此我无法确保它们不会重复。正如您所说,javascript 解决方案过于复杂(有些人没有 javascript)。
  • 为 ID 生成 GUID。
【解决方案2】:

在我看来,最好的办法是重命名所有复选框,方法是在它们的 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>

这样您不会与页面上的其他 id 发生任何冲突,并且单击标签将切换复选框,而无需任何特殊的 javascript 功能。

【讨论】:

    【解决方案3】:

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

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

    这个问题可以用一点 javascript 轻松解决。只需将以下代码放入您页面的一个 js 文件中,即可为 &lt;label&gt; 标记提供以下行为:

    点击标签时:

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

    如果使用id 未找到匹配项,则查找label 的同级,其classlabelfor 属性匹配,并将其聚焦。

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

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

    唉,实际代码:

    $(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();
            }
        })
    });
    

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

    希望这会有所帮助!

    【讨论】:

    • 感谢投反对票的人。回想起来,我的解决方案远非理想。我建议您改用“隐式标签关联”,如以下答案所示:stackoverflow.com/a/8537641/884734
    • 这不仅会导致 W3C 一致性验证器出现问题,而且它也不适用于辅助技术,例如屏幕阅读器。正如您在评论中所写,它们需要隐式标签关联。
    【解决方案4】:

    这里已经解决了: https://stackoverflow.com/a/8537641 就这样吧

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

    【讨论】:

    • 这仅在标签和复选框彼此相邻时有效。
    • @Shawn 原来的帖子就是这样。
    • 我唯一推荐的是将文本放在输入标签之前。否则,完美!
    • 问题是当你必须设置它的样式时。 CSS 中没有父选择器。
    • 在某些布局中可能无法实现,但如果没有 JS,则无法将标签和输入链接起来很简单。这是 WC3 批准的解决方案,不使用链接 ID。如果您真的遇到样式或标记问题,请使用 JS。
    【解决方案5】:

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

    【讨论】:

      【解决方案6】:

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

      【讨论】:

        【解决方案7】:

        我今天为此苦苦挣扎,并认为我可以分享我的结果,因为在 google 的顶级排名中似乎没有其他人。所以这是我的第一个 Stack-Post(诀窍是将复选框拉伸到其他元素上,但使用 z-index 保持它们可点击):

        第一:基础手风琴的学分: https://code-boxx.com/simple-responsive-accordion-pure-css/

        .tab{
            position: relative;
            max-width: 600px;
            z-index:1;
        }
        .tab input{
            padding: 100%;
            position: absolute;
            width: 100%;
            height: 100%;
            opacity: 0;
            z-index:2;
            cursor: pointer;
        }
        .tab label{
            display: block;
            margin-top: 10px;
            padding: 10px;
            color: #fff;
            font-weight: bold;
            background: #2d5faf;
        }
        .tab label span{
            position:relative;
            z-index:3;
            cursor:text;
        }
        .tab .tab-content{
            position:relative;
            background: #ccdef9;
            overflow: hidden;
            transition: max-height 0.3s;
            max-height: 0;
            z-index:3;
        }
        .tab .tab-content p{
            padding: 10px;
        }
        .tab input:checked ~ .tab-content{
            max-height: 100vh;
        }
        .tab label::after{
            content: "\25b6";
            position: absolute;
            right: 10px;
            top: 10px;
            display: block;
            transition: all 0.4s;
        }
        .tab input:checked ~ label::after{
            transform: rotate(90deg);
        }
        <div>
                                    <div class="tab">
                                        <input type="checkbox">
                                        <label><span>Tab 1</span></label>
                                        <div class="tab-content"><p>Should the pace attack?</p></div>
                                    </div>
                                    <div class="tab">
                                        <input type="checkbox">
                                        <label><span>Tab 2</span></label>
                                        <div class="tab-content"><p>Some other Text</p></div>
                                    </div>
                                </div>

        编辑: 很抱歉没有回答最初的问题,但我正在工作,我认为原则很清楚,对吧?

        【讨论】:

          猜你喜欢
          • 1970-01-01
          • 2013-08-28
          • 1970-01-01
          • 2020-09-18
          • 2016-07-03
          • 1970-01-01
          • 2020-03-08
          • 1970-01-01
          • 1970-01-01
          相关资源
          最近更新 更多