如何防止标签内的链接触发复选框? [英] How to prevent a link inside a label from triggering a checkbox?
问题描述
我有这个标签:
<label><input type="checkbox"> I agree to the <a href="terms">terms</a> and would like to continue</label>
然而,标签内的链接打开了一个基础5揭示模态。这样可以正常工作,但点击链接也会选中复选框。
However, the link inside the label opens a foundation 5 reveal modal. This works fine, but clicking on the link also checks the checkbox.
如何在单击链接时阻止选中该复选框?
How can I prevent the checkbox from being checked when the link is clicked?
推荐答案
您应该只需要将事件绑定到调用 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;
});
纯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屋!