自定义提示功能尚未完成



我正在开发基于浏览的文本风格游戏(这是一种使用一些图像/动画的文本游戏,但文本可以传达故事/动作/命令)。我曾经通过prompt("What is your class?");(Warrior,Wizard等)使它起作用,但想创建自己的功能以使其变得更漂亮。在某些代码下方:

/*
    1st value: Message being asked
    2nd value: input field being used
    3rd value: message block where question is presented
*/
var _cprompt = cPrompt('What is your class?', 'dialog-input', 'dialog-text');
alert(_cprompt);

这是实际函数CPROMPT();

/*
Custom prompt class
message: The message shown
inputField: The ID of the txtfield where the user inputs his answer
messageField: The textarea where the response appears
userInput: Empty variable to store the users input
*/
function cPrompt(mssg, inputFieldId, messageFieldId) {
    var message = mssg;
    var inputField = $('#'+inputFieldId);
    var messageField = $('#'+messageFieldId);
    var userInput = "";
    messageField.append(message);
    // Detect enter space being pressed in inputField
    inputField.keyup(function (e) {
        if (e.keyCode == 13) {
            userInput = inputField.val();
        }
    });
}

到目前为止还不错,但是我需要它阻止其他代码执行,直到用户填写响应并击中输入(类似于prompt();),因此在这种情况下,它不会执行alert(_cprompt);一些输入并点击输入。

我尝试使该功能尽可能动态,但请随时添加任何可能使其更快/更易于使用的东西。

感谢您的帮助。

使用回调是事件发生后执行操作的好方法。在这种情况下,该事件将是"用户填写响应"。在此处查看一个工作示例http://jsfiddle.net/q2quk/2/。

<div id="dialog-text"></div>
<input id="dialog-input" />

在CPROMPT函数中,您可以像时间正确时一样运行回调函数。而不是返回值,而是将结果作为参数传递给回调函数。

function cPrompt(mssg, inputFieldId, messageFieldId, callback){
    var message = mssg;
    var inputField = $('#'+inputFieldId);
    var userInput = "";
    cNotify(messageFieldId, message);
    // Detect enter space being pressed in inputField
    inputField.on('keyup', function (e) {
        if (e.keyCode == 13) {
            userInput = inputField.val();
            callback(userInput);
            // If you want the callback to only be executed once,
            // unbind the keyup event afterwards.
            inputField.off('keyup');
            // Empty the input field after processing the user's message.
            inputField.val('');
        }
    });
}

作为如何让您的编码响应用户输入的示例,我创建了此cnotify函数以在对话框文本元素中显示用户输入。

function cNotify(messageFieldId, message){
    $('#' + messageFieldId).append('<div>' + message + '</div>');
}

通过回调使用匿名函数作为CPROMPT函数的参数。

cPrompt('What is your class?', 'dialog-input', 'dialog-text', function(_cprompt){
    // Here you put all the code you want to run after the user pressed enter.
    cNotify('dialog-text', _cprompt);
});

使用回调。

function cPrompt(mssg, inputFieldId, messageFieldId, callback) {
    var message = mssg;
    var inputField = $('#'+inputFieldId);
    var messageField = $('#'+messageFieldId);
    messageField.append(message);
    // Detect enter space being pressed in inputField
    inputField.keyup(function (e) {
            if (e.keyCode == 13) {
                callback(inputField.val());
            }
    });
}
cPrompt('What is your class?', 'dialog-input', 'dialog-text', function (_cprompt) {
    alert(_cprompt);
});

最新更新