如何防止标签内的链接触发复选框?

时间:2014-07-15 10:27:10

标签: javascript jquery html css

我有这个标签:

<label><input type="checkbox"> I agree to the <a href="terms">terms</a> and would like to continue</label>

然而,标签内部的链接打开了一个基础5揭示模态。这样可以正常工作,但点击链接也会检查复选框。

如何在单击链接时阻止检查复选框?

8 个答案:

答案 0 :(得分:16)

You should just need to bind an event to the link that calls event.stopPropagation() and event.preventDefault()

JQuery for all links in labels:

$(document).on("tap click", 'label a', function( event, data ){
    event.stopPropagation();
    event.preventDefault();
    window.open($(this).attr('href'), $(this).attr('target'));
    return false;
});

Pure javascript (you need to set an id on the link you want to follow)

var termLink = document.getElementById('termLink');
var termClickHandler = function(event) {
    event.stopPropagation();    
    event.preventDefault();
    window.open(termLink.href, termLink.target);
    return false;
};
termLink.addEventListener('click', termClickHandler);
termLink.addEventListener('touchstart', termClickHandler);

These expect the link target to be set to _self or _blank to open in the same window or a new window respectively.

答案 1 :(得分:10)

由于多个标签可以指向同一个复选框,因此您可以将文本修改为由两个标签(指向复选框)和中间的锚文本组成。

&#13;
&#13;
<input id="cb" type="checkbox">
<label for="cb">I agree to the</label>
<a href="#">terms</a>
<label for="cb">and would like to continue</label>
&#13;
&#13;
&#13;

使用上述技术,点击链接不会影响复选框的状态,但所有剩余的文本都会生效。

答案 2 :(得分:4)

交互式元素中的交互元素会导致类似这样的功能问题:未定义当您单击a元素内的label元素时发生的情况,反之亦然。为避免这种情况,请从a元素中取出label元素,例如

<label><input type="checkbox">I agree</label> to the <a href="terms">terms</a>
and would like to continue

<input type="checkbox" id="agree"><label for="agree">I agree</label> to the
<a href="terms">terms</a> and would like to continue

答案 3 :(得分:1)

停止在链接上传播click事件。这可以防止点击事件冒泡到标签。

https://developer.mozilla.org/en-US/docs/Web/API/event.stopPropagation

答案 4 :(得分:1)

另一种内联方式:

<label>
     <input type="checkbox"> 
     I aggree to the 
     <span  onclick="event.stopPropagation();">
          <a href="terms">terms</a>
     </span>
     and would like to continue
</label>

答案 5 :(得分:0)

jQuery的:

$('label a').each(function(){
    var $this = $(this),
        span = $('<span onclick="event.stopPropagation();"></span>');
    span.html($this.clone());
    $this.replaceWith(span);
});

答案 6 :(得分:0)

尝试一下。它对我有用

<label><input type="checkbox"> I aggree to the <a href="terms" target="_blank" style="display: inline-block; z-index: 99999999999999999999; position: relative;">terms</a> and would like to continue</label>

答案 7 :(得分:-1)

Try this..
 <label>
      <input type="checkbox" /> I aggree to the <a href="terms">terms</a> and would like to continue
 </label>