html label没有id,如何使用INPUT标签上没有ID属性的LABEL标签的FOR属性

本文讨论了在网页开发中,如何避免因ID冲突导致的checkbox操作问题。作者提出通过NAME属性而非ID关联LABEL与Checkbox,并推荐使用NAME属性一致的机制来确保正确交互。同时,也提到了几种可能的解决方案和场景应用.
摘要由CSDN通过智能技术生成

下面的代码说明了问题的解决方案吗?首先在浏览器中打开代码以便直观地看到问题,而不必在知道要查找的内容之前查看所有代码。如何使用INPUT标签上没有ID属性的LABEL标签的FOR属性

Input ID creates problems

#prologue, #summary { margin: 5em; }

Input ID creates a bug

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:

  • prologue

  • chapter

  • summary

  • etc

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 prologue and summary, 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.

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:

 
 

<label><input type="checkbox" />prologue</label>

and not need to give an ID to the checkboxes. But this only works if the label and checkbox are next to each other.

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?

2010-04-24

Shawn

+1

除了没有明确的问题,这是http://stackoverflow.com/questions/8537621/possible-to-associate-label-with-checkbox-without-using-for-id的重复。 –

2016-02-29 04:02:24

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值