一个链接里面的标签,也触发复选框,如何防止? [英] A link inside a label, also triggers the checkbox, how to prevent?

查看:108
本文介绍了一个链接里面的标签,也触发复选框,如何防止?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有这个标签

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

但是:


  • 标签内的链接打开基础5显示模式

这个工作正常,但点击链接也启用
复选框

This works fine but the click on the link also enables the checkbox.

我如何防止发生这种情况?

thx,

推荐答案

您应该只需要将一个事件绑定到调用 event.stopPropagation() event.preventDefault ()

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

JQuery用于标签中的所有链接:

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(您需要在要关注的链接上设置ID)

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

这些期望链接目标设置为 _self _blank 分别在同一窗口或新窗口中打开。

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

这篇关于一个链接里面的标签,也触发复选框,如何防止?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆