简体   繁体   English

绑定两个JQuery和Ajax函数

[英]Binding two JQuery and ajax functions

I have the follwoing JQuery/AJAX code: 我有下面的JQuery / AJAX代码:

 <script>


    $('.warning-dialog').click(function () {
        alert($(this).data("id"));
    });

    $(function () {
        //twitter bootstrap script
        $("button#delete").click(function () { 
            $.ajax({
                type: "GET",
                url: "deleteArticleType.php",
                data: { 'typeID': $('.warning-dialog').data("id") },
                success: function (msg) {
                    $("#thanks").html(msg)
                    $("#form-content").modal('hide');
                },
                error: function () {
                    alert("failure");
                }
            });
        });
    });
</script>

The first function gets the data-id of a button . 第一个函数获取button的data-id。 The second function calls a PHP page and with the method GET should get the value from the first function. 第二个函数调用PHP页面,使用GET方法应从第一个函数获取值。

I tried the code above but it didn't work. 我尝试了上面的代码,但是没有用。

My question is why and how can I fix it? 我的问题是为什么以及如何解决?

If these are two separate events, disconnected in time and you want to store the value from the first click and then use it in the second click, then you will have to store it somewhere. 如果这是两个单独的事件,时间上已断开连接,并且您要存储第一次单击的值,然后在第二次单击中使用它,则必须将其存储在某个位置。 There are several options, the simplest being a variable. 有几种选择,最简单的是变量。

$(function () {
    var lastClickId;
    $('.warning-dialog').click(function () {
        lastClickId = $(this).data("id");
    });

    //twitter bootstrap script

    // FIXME: you need to add logic here for what to do if lastClickId isn't set yet
    // or create a default behavior in that case
    $("button#delete").click(function () { 
        $.ajax({
            type: "GET",
            url: "deleteArticleType.php",
            data: { 'typeID': lastClickId },
            success: function (msg) {
                $("#thanks").html(msg)
                $("#form-content").modal('hide');
            },
            error: function () {
                alert("failure");
            }
        });
    });
});

Since it looks like you are requiring the first click to happen before the second click can have something to operate on, then you should probably either modify the UI to use different types of controls or you will need to add some error handling if the user doesn't click in the right order. 由于看起来您需要先单击才能进行第二次单击才能进行操作,因此您可能应该修改UI以使用不同类型的控件,或者如果用户没有这样做则需要添加一些错误处理不要按正确的顺序单击。

Actually it should have worked using $('.warning-dialog').data("id") 实际上,它应该使用$('.warning-dialog').data("id")

If your page contains only a single class warning-dialog , you approach will be worked. 如果您的页面仅包含一个warning-dialog类,则可以使用该方法。 It seems you're referring this class to many elements. 看来您正在将该类引用为许多元素。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM