简体   繁体   English

如何将变量设置为文本输入,然后使其出现在屏幕上

[英]How can I set a variable to a text input and then make it appear on screen

I am making a text based game for school and I am stuck with trying to set a variable as an text input. 我正在为学校制作一款基于文本的游戏,但我坚持尝试将变量设置为文本输入。 What I would like to happen is the player type start into the input and it do what is inside of the if statement. 我想发生的是播放器类型从输入开始,并且执行if语句中的内容。 However from there I would like the player to enter a username and then it set the variable of "name" to what they input but with out it saving the name as "start". 但是从那里我希望播放器输入一个用户名,然后将“ name”变量设置为他们输入的内容,但没有将其保存为“ start”。

//js

var name = "";
var beginBeenTo = false;
    if (beginBeenTo == false) {
        if (input == "START") {

            beginBeenTo = true;

            page = page + 1;
            healthPoints = 25;

            soundEveningBreeze.play();
            $("#welcome_message").show().insertBefore("#placeholder").delay(3000).fadeOut(3000);
            $("<br><p class='text'>You there, what is your name?</p>").hide().insertBefore("#placeholder").delay(7000).fadeIn(3000);

            if (input != "" || namingBeenTo == false) {
                name = input;
            }
        }
    }

document.getElementById("print_name").innerHTML = name;

Quite simply, watch for some event ( keyup in my case), check if the input value is START , if so ask for a username. 很简单,注意一些事件(在我的情况下为keyup ),检查输入值是否为START ,如果是这样则要求输入用户名。

 var started = false; var username = ''; $('input').on('keyup', function(){ var tmpValue = $(this).val(); if(started){ username = tmpValue } if(tmpValue === 'START') { started = true; $(this).val('') $(this).attr('placeholder','Username') } $('#username').text(username) }) 
 <script src="https://ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js"></script> <span id="username"></span> <br> <input type="text" placeholder="Type START to play"> 

it could be done with use of function like this : 可以通过使用如下函数来完成:

var name = "";    
$("form").submit(function() {
var input = $("#command_input").val().toUpperCase();
if (input == "START") {
name = $("#input_form").val();
}
}
document.getElementById("print_name").innerHTML = name;

you were missing one of #(hashtag) 您缺少#(#标签)中的一个

And this code would work 而且这段代码可以工作

Thanks & Cheers 谢谢与欢呼

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

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