可以将标签与复选框关联而不使用"for = id"?

D.T*_*ate 66 html javascript css checkbox jquery

我知道有时将标签与复选框关联起来很好:

<input id="something" type="checkbox" value="somevalue" />
<label for="something">this is label text</label>
Run Code Online (Sandbox Code Playgroud)

..但我是否必须使用id来关联它?
我甚至关心的主要原因是因为我喜欢能够点击标签来切换复选框值,但是不喜欢使用id这么简单的想法.

我想我可以使用jQuery切换单击标签的前一个元素(复选框),但也许有一些更简单的我缺少./sf/answers/190454001/看起来像一个解决方案,但用户说它在IE中不起作用.

Mad*_*iha 162

是的,将输入放在标签内.

<label><input type=checkbox name=chkbx1> Label here</label>
Run Code Online (Sandbox Code Playgroud)

请参阅HTML规范中的隐式标签关联.

  • +1最佳解决方案 - 请参阅[隐式标签关联]的HTML规范(http://www.w3.org/TR/html4/interact/forms.html#h-17.9.1). (3认同)
  • 这在IE中有用吗?http://stackoverflow.com/a/2720771/923817建议不要 (3认同)
  • 限制(根据规范):*请注意,当表格用于布局时,不能使用此技术,标签位于一个单元格中,其关联控件位于另一个单元格中.* (3认同)

ego*_*xyz 5

演示:JsFiddle

.c-custom-checkbox {
  padding-left: 20px;
  position: relative;
  cursor: pointer;
}
.c-custom-checkbox input[type=checkbox] {
  position: absolute;
  opacity: 0;
  overflow: hidden;
  clip: rect(0 0 0 0);
  height: 15px;
  width: 15px;
  padding: 0;
  border: 0;
  left: 0;
}
.c-custom-checkbox .c-custom-checkbox__img {
  display: inline;
  position: absolute;
  left: 0;
  width: 15px;
  height: 15px;
  background-image: none;
  background-color: #fff;
  color: #000;
  border: 1px solid #333;
  border-radius: 3px;
  cursor: pointer;
}
.c-custom-checkbox input[type=checkbox]:checked + .c-custom-checkbox__img {
  background-position: 0 0;
  background-color: tomato;
}
Run Code Online (Sandbox Code Playgroud)
<label class="c-custom-checkbox">
  <input type="checkbox" id="valueCheck" />
  <i class="c-custom-checkbox__img"></i>Some Label
</label>
Run Code Online (Sandbox Code Playgroud)