jquery自定义事件返回值 [英] jquery custom events return value

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

问题描述

我正在尝试了解有关jquery自定义事件的更多信息,因此我制作了这个简单的代码来进行测试:

I am trying to learn more about jquery custom events so I have made this simple code to make tests:

<!DOCTYPE html>
<html>
    <head>
        <title>Jquery custom events</title>
        <script src="http://ajax.googleapis.com/ajax/libs/jquery/1.7.2/jquery.min.js"></script>
        <script>
            $(function(){
                $('#link1').click(function(){
                    var that = $(this);
                    $.ajax({
                        url: "http://localhost/jquery/index.html",

                        beforeSend: function(event){ // if returned false, stops ajax request
                           return that.trigger('ajax:beforesend',[{p1: '1'},{p2: '2'}]);

                        },
                        success: function(){
                            that.trigger('ajax:success');
                        },
                        error: function(){
                        }
                    });

                    return false;
                });

                $('#link1').bind('ajax:beforesend',function(e,data,data2){
                    alert("success"+data2.p2);
                    return false;
                });

                $('#link1').bind('ajax:success',function(e){
                    alert("success");

                });
            });
        </script>
    </head>

    <body>
        <a id="link1">link1</a>

        <div id="box" style="width:500px;height:150px;background-color: gray;margin-top: 50px;">
            result
        </div>
    </body>

</html>

我的问题是:在beforesend函数中,如果触发的结果,我想中止ajax请求自定义事件是假但不起作用,
我缺少什么?

My question is: in the beforesend function i want to abort the ajax request if the result of the triggered custom event is false but is not working, What i am missing?

编辑:请不要专注于beforesend功能。我真正想要的是如何将自定义事件结果(例如true或false)返回到调用事件的位置(在本例中为send函数之前)。正如我所说,这只是样板代码。不是真实的世界项目。

Please dont be focus on beforesend function. What i really want is how to return the custom event result (example true or false) to where the event was called (in this case before send function). As I said this is just boilerplate code. Not a real world project.

推荐答案

beforeSend是一个Ajax事件。在beforeSend函数中返回false将取消请求。从jQuery 1.5开始,无论请求的类型如何,都会调用beforeSend选项。

beforeSend is an Ajax Event. Returning false in the beforeSend function will cancel the request. As of jQuery 1.5, the beforeSend option will be called regardless of the type of request.

请在此处检查beforesend ajax事件处理程序并尝试 http://api.jquery.com/jQuery.ajax/

Please check the beforesend ajax event handler here and try http://api.jquery.com/jQuery.ajax/

很可能你的问题出在 beforesend 函数中。

Most probably your problem lies within the beforesend function.

这篇关于jquery自定义事件返回值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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