<a> tag inside <label> tag not triggering checkbox

时间:2017-02-04 07:45:29

标签: javascript jquery html

I have to use <a> inside a <label> tag. Because there are many css styles only apply to <a> in our current system. The <a> tag is not linking to any pages but for styling/hovering.

See code below:

<input type="checkbox" id="my-id">
<label for="my-id"><a href="javascript:void(0)">Some text</a></label>

But when clicking on "Some text", it doesn't toggle the checkbox status.

I've tried $.preventDefault()on the <a> tag but doesn't work.

What should i do to make the <a> behaves like a label?

6 个答案:

答案 0 :(得分:3)

请勿仅将<a>用于样式设置。请改用标签上的类。

.my-link-style {
  /* To match the cursor style for an <a> */
  cursor: pointer;
  
  /* Add more styles here */
}
<input type="checkbox" id="my-id" />
<label for="my-id" class="my-link-style">Some text</label>

答案 1 :(得分:3)

如果您从href元素中删除a属性,则点击该文本将切换复选框。

<input type="checkbox" id="my-id">
<label for="my-id"><a>Some text</a></label>

作为HTML规范states

  

hrefa元素的area属性不是必需的

答案 2 :(得分:2)

只需将锚元素放在标签元素的外部即可。

&#13;
&#13;
<input type="checkbox" id="my-id">
<a href="javascript:void(0)"><label for="my-id">Some text</label></a>
&#13;
&#13;
&#13;

答案 3 :(得分:1)

更新:这个答案是在编辑之前给出的,现在它已经失效,但是,我会把它留给那些有用的

提供apointer-events: none

label[for="my-id"] {
  cursor: pointer;
}
label[for="my-id"] a {
  pointer-events: none;
}
<input type="checkbox" id="my-id">
<label for="my-id"><a href="#">Some text</a></label>

如果您需要支持旧浏览器,请使用伪元素来覆盖它

label[for="my-id"] {
  cursor: pointer;
  position: relative;
}
label[for="my-id"]::after {
  content:  ' ';
  position: absolute;
  left: 0; top: 0;
  right: 0; bottom: 0;
}
<input type="checkbox" id="my-id">
<label for="my-id"><a href="#">Some text</a></label>

答案 4 :(得分:1)

<input type="checkbox" id="my-id">
<label for="my-id"><a href="javascript:void(0)" target="my-id">Some text</a></label>
<script>
  document.querySelector("label[for=my-id] > a")
  .onclick = function(e) {
    var el = document.getElementById(
      this.parentElement.htmlFor
    );
    el.checked = !el.checked;
  }
</script>

答案 5 :(得分:0)

您需要撤消,在标签中包含标签:

<input type="checkbox" id="my-id" >
<a href="javascript:void(0)"><label for="my-id">Some text</label></a>

JSFiddle