代码之家  ›  专栏  ›  技术社区  ›  Jichao

为什么javascript全局变量不是全局变量?

  •  1
  • Jichao  · 技术社区  · 14 年前

    我有一个外部JS文件处理删除一些元素。根据结果,我将决定是否需要刷新页面。

    var deleted = 0; // first assume not deleted 
    
    $(function() {
        $("#action a.action-delete").click(function() {
            var id = $(this).parent().parent().attr("id");
            $.get("modify-sale.php", { "id" : id, "action" : "delete" }, function (data) { deleted = 1;  }, "text");
            if (deleted) return true; // if success then refresh
            else return false; // else does not refresh
        });
    

    不,问题是我不能改变全局变量 deleted 在jQuery事件处理程序中。我可以保证删除操作是成功的,但是这个变量不会将其值更改为1。

    为什么?

    2 回复  |  直到 14 年前
        1
  •  5
  •   meder omuraliev    14 年前

    deleted if else

        2
  •  0
  •   Jichao    14 年前
    $("#action a.action-delete").click(function() {
        var id = $(this).parent().parent().attr("id");
        $.ajax({
            "url" :  "modify-sale.php",
            "type" : "GET",
            "data" : { "id" : id, "action" : "delete" },
            "dataType" : "text",
            "async" : false,
            "success" : function(data) {
                if (data == 'success') {
                    $("#msg").text("delete success").show();
                    $("#msg").fadeOut(1000);
                    deleted = 1;
                } else {
                    $("#msg").text("delete failed, plesase try later").show();
                    $("#msg").fadeOut(5000);
                }
            },
            "error" : function() {
                $("#msg").text("delete failed, please try later").show();
                $("#msg").fadeOut(5000);
            }
        });
        if (deleted) return true;
        else return false;
    });