![](/img/trans.png)
[英]Shorthand for calling a function with an argument more than once in JavaScript/jQuery?
[英]JavaScript - Calling the click function more than once would not work
我正在制作一个文本冒险游戏,它将要求用户以html元素的形式输入用户信息,然后使用click函数将用户输入信息发送给JavaScript:
<!-- HTML CODE -->
<div class="game">
<div id="gamebox">
<a name="game"></a>
<!-- Javascript writes to here (if it works :( ) -->
</div>
<div id="inputbox">
<input type="text" id="userinput" placeholder="Input" value="" />
<a href="#game" id="btn-quest" class="button" style="float: right">Go!</a>
</div>
</div>
如您在上面看到的,我有一个元素和一个“ Go!”。 按钮,将其发送到我的JavaScript代码。 在JavaScript中,首先定义3个变量,将在其中输出文本。
//JavaScript Code
var txt_input = $("#userinput");
var btn_quest = $("#btn-quest");
然后我将定义2个其他函数,这使我可以写入。 我将拥有其他功能,用于文本冒险游戏的故事情节。 但是,问题的根源在于我似乎无法超越第二个事件。 这是我的活动:
function wakeUp() {
displayGame("You wake up, at stackoverflow. West or east? [Choose 'west' or 'east']");
btn_quest.on({
"click": function() {
// Begin input preproccessing
var input = txt_input.val().toLowerCase();
// If/else block for choice here
if (input === "west") {
//Paste btn_quest here for new event
goWest();
} else if (input === "east") {
//Paste btn_quest here for new event
goEast();
} else {
//Error handler - do not modify
txt_input.val("Error - enter a valid choice");
}
//End of if else block body
}
});
第一个事件函数可以完美运行,并写入我的html,并接受用户的第一个选择。 但是,在下一个事件中,无论它是什么(goEast()或goWest()),我的程序都会显示“错误-输入有效选择”。 现在,我的假设是“开关”功能无法正常工作。 但是,老实说我不知道。 这是什么问题,我该如何解决? 除了具有不同的displayGame()字符串和指向其他事件函数的链接之外,其他事件函数(例如goEast)与唤醒函数完全相同。
为了使我的代码简短,我没有包括完整的代码-但如果需要,这里是完整的html / css / javascript: http : //plnkr.co/edit/55heHh4k5QEIVYdBrWGB?p=preview
编辑:我试图实现建议,像这样:但是似乎JavaScript甚至不再获得用户输入。 当我尝试提交用户的回复时,什么都没有发生。 什么地方出了错? 我在游戏中的所有功能都做了相同的事情:
function wakeUp() {
displayGame("You wake up at stackoverflow again, but it didn't work. Go West or east again?");
// btn_quest.off("click").on("click",function()){
btn_quest.off("click").on;
"click", function() {
// Begin input preproccessing
var input = txt_input.val().toLowerCase();
// If/else block for choice here
if (input === "walk") {
//Paste btn_quest here for new event
walkToWork();
} else if (input === "bus") {
//Paste btn_quest here for new event
busToWork();
} else {
//Error handler - do not modify
txt_input.val("Error - enter a valid choice");
}
//End of if else block body
};
//End of function. Copy until line under this comment V
}
我做错了什么? 您可以举一个使用此功能的例子吗?
您需要查看所有代码才能看到问题。 原因是因为您一直绑定到元素,所以触发了多个单击事件。 您需要删除最后一次点击
btn_quest.off("click").on("click",function(){});
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.