0

我最近从常规的 JavaScript 提示切换到了 jQuery 插件的“Alertify”提示。但是,当我将变量定义为提示的响应,并在以后的警报中使用该变量时,它会改为打印“[object Object]”。经过几个小时的谷歌搜索和测试,我仍然没有想出答案。

这是我的代码:

do {
    var fullLoop = false;
    var user = alertify.prompt("What is your name?", function (e, str) {
        if (e) {
            user.toUpperCase();
            if (str.length === 0) {
                alertify.alert("Please enter your name.");
                fullLoop = true;
            }
        } else {
            alertify.alert("Please enter your name.");
            fullLoop = true;
        }
    }, "Name");
    do {
        var bestLoop = false;
        var best = alertify.prompt("So " + user + ", what is your greatest ability, STRENGTH, SPEED, or SMARTS?", function (e, str) {
        if (e) {
            best.toUpperCase();
            if (best === "STRENGTH" || best === "SPEED" || best === "SMARTS") {
            var offset = options.indexOf(best);
            if (offset != -1) {
                options.splice(offset, 1);
            }
        } else {
            alert("Please choose either STRENGTH, SPEED, or SMARTS as your greatest ability.");
            bestLoop = true;
        }
        } else {
            alertify.alert("Please choose either STRENGTH, SPEED, or SMARTS as your greatest ability.");
            bestLoop = true;
        }
    }, "Greatest Ability");
    } while (bestLoop);
    alertify.alert("Great! So " + best + " is yor greatest ability.");
} while (fullLoop);

你可以看到我在这里遇到的错误。

我还注意到我if关于字符串的陈述被忽略了,我假设有一个连接,但它是什么?我没有发现任何错误,所以我是否错误地使用了 Alertify?

4

2 回答 2

0

我对 alterify 了解不多,但看起来您正在尝试显示 JSON 对象。试试 JSON.stringify(user) 看看你会得到什么。可能是这样的

{ "Name": "Paul" }

如果是这样,你会想要做

alertify.prompt("So " + user.Name + ", what is your greatest ability, STRENGTH, SPEED, or SMARTS?"

或者可能

alertify.prompt("So " + JSON.stringify(user.Name) + ", what is your greatest ability, STRENGTH, SPEED, or SMARTS?"

希望这可以帮助!

于 2013-07-03T02:52:08.897 回答
0

您对 alertify 插件的使用是错误的,它的 prompt 方法是一个异步方法,并且所有使用该方法的操作都必须在回调中完成。

缩小版如下

var options = ["STRENGTH", "SPEED", "SMARTS"];
alertify.alert("Before we begin our journey, let's learn a little bit  about you.");

alertify.prompt("What is your name?", function (e, str) {
    if (e) {
        var  user = str.toUpperCase();

        alertify.prompt("So " + user + ", what is your greatest ability, STRENGTH, SPEED, or SMARTS?", function (e, str) {
            if (e) {
                var best = str.toUpperCase();
                if (best === "STRENGTH" || best === "SPEED" || best === "SMARTS") {
                    var offset = options.indexOf(best);
                    if (offset != -1) {
                        options.splice(offset, 1);
                    }
                    alertify.alert("Great! So " + best + " is yor greatest ability.");        
                } else {
                }
            } else {
            }
        }, "Greatest Ability");
    } else {
    }
}, "Name");

演示:小提琴

于 2013-07-03T03:03:32.620 回答