我有这个标签:
<label><input type="checkbox"> I agree to the <a href="terms">terms</a> and would like to continue</label>
然而,标签内的链接会打开基础5版本的reveal模态框。这个功能是正常的,但点击链接也会选中复选框。
我该如何防止在单击链接时选中复选框?
我有这个标签:
<label><input type="checkbox"> I agree to the <a href="terms">terms</a> and would like to continue</label>
然而,标签内的链接会打开基础5版本的reveal模态框。这个功能是正常的,但点击链接也会选中复选框。
我该如何防止在单击链接时选中复选框?
你只需要将事件绑定到链接上,调用event.stopPropagation()
和event.preventDefault()
即可。
JQuery用于标签中的所有链接:
$(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)
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
,分别在相同窗口或新窗口中打开。
由于多个标签可以指向同一个复选框,因此您可以修改文本以包括两个标签(指向复选框)和中间的锚文本。
<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>
使用上述技巧,点击链接不会影响复选框的状态,但所有其余文本都会。
另一种内联方式:
<label>
<input type="checkbox">
I agree to the
<span onclick="event.stopPropagation();">
<a href="terms">terms</a>
</span>
and would like to continue
</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
https://developer.mozilla.org/en-US/docs/Web/API/event.stopPropagation
试试这个。对我有效。
<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>
jQuery:
$('label a').each(function(){
var $this = $(this),
span = $('<span onclick="event.stopPropagation();"></span>');
span.html($this.clone());
$this.replaceWith(span);
});
请试一下这个...
<label>
<input type="checkbox" /> I agree to the <a href="terms">terms</a> and would like to continue
</label>