Jquery 在单击事件中使用StopRopagation
在类为“element”的div中有一个锚 但我的问题是确认事件会一次又一次地触发。我认为这是因为均匀传播。经过研究,我发现我可以使用post中的Jquery 在单击事件中使用StopRopagation,jquery,events,stoppropagation,Jquery,Events,Stoppropagation,在类为“element”的div中有一个锚 但我的问题是确认事件会一次又一次地触发。我认为这是因为均匀传播。经过研究,我发现我可以使用post中的e.stopPropagation()。但我不知道这里怎么能用这个 编辑 确认框中的消息“您想注销吗?”是从数据库中动态获取的,因此我无法在代码中硬编码。试试看 onclick="return confirm('Do you want to logout?');window.event.cancelBubble = true;" 或 onclick=
e.stopPropagation()
。但我不知道这里怎么能用这个
编辑
确认框中的消息“您想注销吗?”是从数据库中动态获取的,因此我无法在代码中硬编码。试试看
onclick="return confirm('Do you want to logout?');window.event.cancelBubble = true;"
或
onclick="javascript:event.stopPropagation();return confirm('Do you want to logout?');"
您可以使用:
$('.subTop a').on('click', function (e) {
e.stopPropagation();
});
不过,我同意@ink.robot的说法,为了避免这种情况,您的代码的结构应该更好。试试以下方法:
HTML:
<div class="element logout">
<div class="subTop">
<a href="home.jsp" class="testa" >Log Out</a>
</div>
</div>
jQuery(".element").click(function(e){
e.preventDefault();
if( confirm('Do you want to logout?'))
{
//console.log(jQuery(this).parents('.element'));return;
if(jQuery(this).hasClass('logout'))
{
window.location.href='logout.jsp';
}
else
{
window.location.href='home.jsp';
}
}
});
测试小提琴:这是基于我认为你想要的一些假设。从评论和问题中我了解到,如果外部div没有logout类,则应将用户发送到“home.jsp”,如果有,则发送到“logout.jsp”。如果这是正确的,您可以将html压缩到
<div class="element logout">
<div class="subTop">
<a href="home.jsp" data-confirmmsg="Do you want to logout?" >Log Out</a>
</div>
</div>
Javascript的第一部分只是将
标记作为链接禁用。除了将事件传播到外部元素之外,什么也不会发生(如果单击实际上是在链接上,那么我们仍然希望通过`div标记来处理它)。JavaScript的第二部分首先检查注销类是否存在,并相应地设置href。最后,如果用户被发送到“logout.jsp”,则会显示确认框并测试返回值。我认为您希望根据div class
、logout
或not
重定向页面。如果注销类
那么注销.jsp
如果div没有注销类
那么home.jsp
。对吗?在else子句中有一个无限循环-click()。首先修改您的逻辑-例如stopPropagation()或取消事件气泡是一个更糟糕的补丁-您的代码本身应该足够干净,可以优雅地退出,而不会受到任何黑客攻击。我相信这段代码可以重新编写得非常干净-你能详细说明你想要完成什么吗?@arjuncc现在试试上面的代码。你的代码在这方面是好的+1,但它不能解决我的问题。我在确认框中有动态内容(来自数据库)。所以我不能硬编码“你想注销吗?”你可以为
添加数据属性,然后在jquery
中像如果(确认($(this.attr('data')))
您好,先生,我尊重您的意见,但是,我在确认框中有动态内容(来自数据库)。所以我不能硬编码“你想注销吗?”(我在帖子中添加了它作为编辑)@arjuncc您不必这样做。只需将消息作为数据发送到a标记。请参阅更新
jQuery(".element").click(function(e){
e.preventDefault();
if( confirm('Do you want to logout?'))
{
//console.log(jQuery(this).parents('.element'));return;
if(jQuery(this).hasClass('logout'))
{
window.location.href='logout.jsp';
}
else
{
window.location.href='home.jsp';
}
}
});
<div class="element logout">
<div class="subTop">
<a href="home.jsp" data-confirmmsg="Do you want to logout?" >Log Out</a>
</div>
</div>
jQuery(".subTop>a").click(function(e){
e.preventDefault();
});
jQuery(".element").click(function(e){
var self = jQuery(this),
isLogout = self.hasClass('logout')
anchor = self.find(".subTop>a")
href = isLogout ? "logout.jsp" : anchor.attr('href');
if(!isLogout || (isLogout && confirm(anchor.data('confirmmsg'))))
{
window.location.href=href;
}
});