从 jQuery 点击事件返回 false [英] return false from jQuery click event

查看:26
本文介绍了从 jQuery 点击事件返回 false的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有这样设置的点击事件:

I have click events set up like this:

$('.dialogLink')
    .click(function () {
        dialog(this);
        return false;
    });

所有的都有一个return false"

The all have a "return false"

有人能解释一下这是做什么的以及是否需要它吗?

Can someone explain what this does and if it's needed?

推荐答案

当您从事件处理程序返回 false 时,它会阻止该事件的默认操作并阻止事件通过 DOM 冒泡.也就是说,它相当于这样做:

When you return false from an event handler it prevents the default action for that event and stops the event bubbling up through the DOM. That is, it is the equivalent of doing this:

$('.dialogLink')
   .click(function (event) {
       dialog(this);
       event.preventDefault();
       event.stopPropagation();
});

如果 '.dialogLink'<a> 元素,则其默认点击操作是导航到 href.从点击处理程序返回 false 可以防止这种情况发生.

If '.dialogLink' is an <a> element then its default action on click is to navigate to the href. Returning false from the click handler prevents that.

至于您的情况是否需要它,我猜答案是肯定的,因为您希望显示一个对话框以响应点击而不是导航.如果您放置了点击处理程序的元素在点击时没有默认操作(例如,当您单击 div 时通常没有任何反应),那么您不需要返回 false,因为没有什么可以取消.

As for whether it is needed in your case, I would guess the answer is yes because you want to display a dialog in response to the click rather than navigating. If the element you've put the click handler on does not have a default action on click (e.g., normally nothing happens when you click a div) then you needn't return false because there's nothing to cancel.

如果你想对点击做一些事情,但让默认导航继续,那么不要返回 false.

If you want to do something in response to the click but let the default navigation continue then do not return false.

进一步阅读:

这篇关于从 jQuery 点击事件返回 false的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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