kev*_*ius 26 html javascript css jquery
我有这个标签:
<label><input type="checkbox"> I agree to the <a href="terms">terms</a> and would like to continue</label>
Run Code Online (Sandbox Code Playgroud)
但是,标签内部的链接打开了一个基础5揭示模态.这样可以正常工作,但点击链接也会选中复选框.
如何在单击链接时阻止选中复选框?
小智 17
您应该只需要将事件绑定到调用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;
});
Run Code Online (Sandbox Code Playgroud)
纯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);
Run Code Online (Sandbox Code Playgroud)
这些期望链接目标分别设置为_self或_blank在同一窗口或新窗口中打开.
Dan*_*eld 11
由于多个标签可以指向同一个复选框,因此您可以将文本修改为由两个标签(指向复选框)和中间的锚文本组成.
<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>Run Code Online (Sandbox Code Playgroud)
使用上述技术,单击链接不会影响复选框的状态,但所有剩余文本都会影响复选框的状态.
另一种内联方式:
<label>
<input type="checkbox">
I agree to the
<span onclick="event.stopPropagation();">
<a href="terms">terms</a>
</span>
and would like to continue
</label>
Run Code Online (Sandbox Code Playgroud)
交互元素内的交互元素会导致这样的功能问题:当您单击a元素内的label元素时会发生什么情况是不确定的,反之亦然。为避免这种情况,将a元素从元素中取出label,例如
<label><input type="checkbox">I agree</label> to the <a href="terms">terms</a>
and would like to continue
Run Code Online (Sandbox Code Playgroud)
或者
<input type="checkbox" id="agree"><label for="agree">I agree</label> to the
<a href="terms">terms</a> and would like to continue
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
18654 次 |
| 最近记录: |