Javascript "return false" 是什么意思?做?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/10729198/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-24 02:40:36  来源:igfitidea点击:

What does "return false;" do?

javascriptjqueryajax

提问by Dmitri

I wrote a webpage where a user can enter a log entry that is stored on a database and then retrieved and printed on the page using ajax. I am still quite new to ajaxand was wondering if somebody could please explain to me what does return false;do at the end of my code? and is it even necessary?

我写了一个网页,用户可以在其中输入存储在数据库中的日志条目,然后使用ajax. 我仍然很ajax陌生,想知道是否有人可以向我解释return false;在我的代码末尾做什么?甚至有必要吗?

If I put the second ajax code after the return falsethe code does not work! can you please explain to me why?

如果我把第二个ajax代码放在代码之后就不行了return false!你能解释一下为什么吗?

//handles submitting the form without reloading page 
$('#FormSubmit').submit(function(e) {
    //stores the input of today's data
    var log_entry = $("#LogEntry").val();
    // prevent the form from submitting normally
    e.preventDefault();

    $.ajax({
        type: 'POST',
        url: 'behind_curtains.php',
        data: {
            logentry: log_entry
        },
        success: function() {
            alert(log_entry);
            //clears textbox after submission
            $('#LogEntry').val("");
            //presents successs text and then fades it out
            $("#entered-log-success").html("Your Entry has been entered.");
            $("#entered-log-success").show().fadeOut(3000);
        }
    });
    //prints new log entries on page upon submittion
    $.ajax({
        type: 'POST',
        url: '/wp-content/themes/childOfFanwood/traininglog_behind_curtains.php',
        data: {
            log_entries_loop: "true"
        },
        success: function(data) {
            alert(data);
            $("#log-entry-container").html("");
            $("#log-entry-container").html(data);
        }
    });
    return false;
});
?

回答by gdoron is supporting Monica

What I'll write here is true for jQuery events,
For vanilla javascript events read @T.J. Crowder comment at the bottom of the answer

我将在这里写的内容适用于jQuery 事件
对于 vanilla javascript 事件,请阅读答案底部的 @TJ Crowder 评论



return falseinside a callback prevents the default behaviour. For example, in a submitevent, it doesn't submit the form.

return false在回调中防止默认行为。例如,在一个submit事件中,它不提交表单。

return falsealso stops bubbling, so the parents of the element won't know the event occurred.

return false也停止冒泡,所以元素的父元素不会知道事件发生。

return falseis equivalent to event.preventDefault()+ event.stopPropagation()

return false相当于event.preventDefault()+event.stopPropagation()

And of course, all code that exists after the return xxxline won't be executed. (as with all programming languages I know)

当然,在该return xxx行之后存在的所有代码都不会被执行。(和我知道的所有编程语言一样)

Maybe you find this helpful:
Stop event bubbling - increases performance?

也许你觉得这很有帮助:
停止事件冒泡 - 提高性能?



A "real"demo to explain the difference between return falseand event.preventDefault():

一个“真实”的演示讲解的区别return falseevent.preventDefault()

Markup:

标记:

<div id="theDiv">
    <form id="theForm" >
        <input type="submit" value="submit"/> 
    </form>
</div>?

JavaScript:

JavaScript:

$('#theDiv').submit(function() {
    alert('DIV!');
});
$('#theForm').submit(function(e) {
    alert('FORM!');
    e.preventDefault();
});?

Now... when the user submit the form, the first handler is the form submit, which preventDefault()-> the form won't be submitted, but the event bubbles to the div, triggering it's submit handler.

现在...当用户提交表单时,第一个处理程序是表单提交,它preventDefault()-> 表单不会被提交,但事件冒泡到 div,触发它的提交处理程序。

Live DEMO

现场演示

Now, if the form submit's handler would cancel the bubbling with return false:

现在,如果表单提交的处理程序将取消冒泡return false

$('#theDiv').submit(function() {
    alert('DIV!');
});
$('#theForm').submit(function(event) {
    alert('FORM!');
    return false;   
    // Or:
    event.preventDefault(); 
    event.stopPropagation();
});?

The div wouldn't even know there was a form submission.

div 甚至不知道有表单提交。

Live DEMO

现场演示



What does return falsedo in vanilla javascript events

return false在 vanilla javascript 事件中做什么

return false from a DOM2 handler (addEventListener) does nothing at all (neither prevents the default nor stops bubbling; from a Microsoft DOM2-ish handler (attachEvent), it prevents the default but not bubbling; from a DOM0 handler (onclick="return ..."), it prevents the default (provided you include the return in the attribute) but not bubbling; from a jQuery event handler, it does both, because that's a jQuery thing. Details and live tests here – T.J. Crowder

从 DOM2 处理程序 ( addEventListener)返回 false根本不做任何事情(既不阻止默认值也不停止冒泡;从 Microsoft DOM2-ish 处理程序 ( attachEvent) 中,它阻止默认值但不冒泡;从 DOM0 处理程序 ( onclick="return ...") 中,它阻止默认值(假设您在属性中包含返回值)但不冒泡;从 jQuery 事件处理程序中,它可以同时执行这两项操作,因为那是 jQuery 的事情。此处的详细信息和实时测试 – TJ Crowder

回答by Pavel Strakhov

Any code after returnstatement in a function will never be executed. It stops executing of function and make this function return value passed (falsein this case). Your function is "submit" event callback. If this callback returns false, form will not be submitted actually. Otherwise, it will be submitted as it would do without JavaScript.

return函数中语句之后的任何代码都不会被执行。它停止执行函数并使该函数返回值传递(false在这种情况下)。您的功能是“提交”事件回调。如果这个回调返回false,表单将不会被实际提交。否则,它将像没有 JavaScript 一样被提交。

回答by ahren

In this instance, return false;prevents the default action (which is the form submitting).

在这种情况下,return false;阻止默认操作(即表单提交)。

Although it's probably better to use e.preventDefault();

虽然它可能更好地使用 e.preventDefault();

回答by pbaris

because of ajax you do not want your form to be submitted with the normal way. So you have to return false in order to prevent the default behavior of the form.

由于 ajax,您不希望以正常方式提交表单。所以你必须返回 false 以防止表单的默认行为。

回答by The man

The return statement ends function execution This is important. Using return causes your code to short-circuit and stop executing immediately, preventing the next line of code from executing

return 语句结束函数执行 这很重要。使用 return 会导致您的代码短路并立即停止执行,从而阻止执行下一行代码