How to prevent a link inside a label from triggering a checkbox?

前端 未结 8 1464
难免孤独
难免孤独 2021-01-03 18:41

I have this label:

相关标签:
8条回答
  • 2021-01-03 19:09

    Try this . It works for me

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

    0 讨论(0)
  • 2021-01-03 19:11

    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.

    0 讨论(0)
  • 2021-01-03 19:11

    Since multiple labels can point to the same checkbox, you can modify the text to consist of two labels (pointing to the checkbox) and the anchor text in the middle.

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

    Using the above technique, clicking on the link doesn't effect the state of the checkbox, yet all the remaining text does.

    0 讨论(0)
  • 2021-01-03 19:15

    Try this, please...

     <label>
          <input type="checkbox" /> I agree to the <a href="terms">terms</a> and would like to continue
     </label>
    
    0 讨论(0)
  • 2021-01-03 19:16

    Another inline way:

    <label>
         <input type="checkbox"> 
         I aggree to the 
         <span  onclick="event.stopPropagation();">
              <a href="terms">terms</a>
         </span>
         and would like to continue
    </label>
    
    0 讨论(0)
  • 2021-01-03 19:24

    jQuery:

    $('label a').each(function(){
        var $this = $(this),
            span = $('<span onclick="event.stopPropagation();"></span>');
        span.html($this.clone());
        $this.replaceWith(span);
    });
    
    0 讨论(0)
提交回复
热议问题