如何使用 LABEL 标记的 FOR 属性而不使用 INPUT 标记上的 ID 属性

下面的代码中说明的问题是否有解决方案?首先在浏览器中打开代码,直奔主题,在知道要查找什么之前不必查看所有代码。

<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>
82227 次浏览

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.

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.

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

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

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

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:

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.

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.

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.

Hope this helps!

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

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

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

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

i was struggling with this today and thought i could share my result, because it seems there're no others in googles top-ranks. So here's my first Stack-Post (the trick is to stretch the checkbox over the other elements but keeping them clickable by using z-index):

first: credits for the base accordion: 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>

EDIT: sorry for not answering the original question but i'm on work and i think the principle is clear, right?