我什么时候应该在jquery函数中使用return false? [英] When should I use return false in jquery function?

查看:187
本文介绍了我什么时候应该在jquery函数中使用return false?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我发现很多这样的功能:

I found lots of functions like this one:

$(function() {
    $("body a").click(function() {
        alert(this.innerHTML);
        return false;
    });
});

和<$之间有什么区别? c $ c> $(this)在jquery中?

What's the difference between this and $(this) in jquery?

它们都有一行返回false; - 我不知道何时应该在jquery函数中使用 return false 并且不知道它的用途是什么?

They all have a line return false; - I don't know when I should use return false in jquery function and don't know what's the use of it?

推荐答案

根据 jQuery事件:停止(误)使用返回假(存档链接),返回 false 调用时执行三个任务:

According to jQuery Events: Stop (Mis)Using Return False (archived link), returning false performs three tasks when called:


  1. event.preventDefault();

  2. event.stopPropagation() ;

  3. 停止回调执行并在调用时立即返回。

取消所需的唯一操作默认行为是 preventDefault()。发出返回false; 可以创建脆弱的代码。通常你只需要这样:

The only action needed to cancel the default behaviour is preventDefault(). Issuing return false; can create brittle code. Usually you'd want just this:

$("a").on( 'click', function (e) {
    // e == our event data
    e.preventDefault();
});

其次this是javascript中的DOM元素,$(this)是jQuery element
引用DOM元素。请阅读
jQuery的内容:揭秘

And secondly "this" is a DOM element in javascript and "$(this)" is a jQuery element that references the DOM element. Read more on the topic at jQuery's this: demystified.

这篇关于我什么时候应该在jquery函数中使用return false?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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