我试图在文本字段中构建历史记录,用户可以按下向上箭头并查看在字段中写入的上一个文本。
到目前为止,我已设法跟踪以前的输入:http://jsfiddle.net/gLhkr3mL/
var prevCommand = [];
var commandCount = 0;
var keyCount = 0;
$("#form-prompt").on("submit", function (e) {
commandCount++;
keyCount = 0;
prevCommand[commandCount] = $('#textTest').val();
e.preventDefault();
$('#textTest').val('');
});
$(document).keydown(function(event){
if(event.which == 38 && $("#textTest").is(":focus")){
keyCount++;
if(typeof prevCommand[keyCount] !== "undefined") {
$('#res').append('<hr>'+prevCommand[keyCount]);
}
}else if(event.which == 40 && $("#command-text").is(":focus")) {
}
});
我面临的问题是,在这种情况下,历史记录将以错误的顺序显示,因为我希望最新的输入首先出现,等等。
答案 0 :(得分:2)
见this updated fiddel。现在你要从数组的第一个索引开始。您必须更改它,以便从最后一个元素转到第一个元素。还可以添加一个提交按钮,以便测试bahavour。
var prevCommand = [];
var commandCount = 0;
var keyCount = 0;
$("#form-prompt").on("submit", function (e) {
commandCount++;
keyCount = 0;
prevCommand[commandCount] = $('#textTest').val();
e.preventDefault();
$('#textTest').val('');
});
$(document).keydown(function(event){
if(event.which == 38 && $("#textTest").is(":focus")){
keyCount++;
var index = prevCommand.length-keyCount;
if(typeof prevCommand[index ] !== "undefined") {
$('#res').append('<hr>'+prevCommand[index]);
}
}else if(event.which == 40 && $("#command-text").is(":focus")) {
}
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<form id='form-prompt'>
<input type='text' id='textTest'>
<input type="submit" />
</form>
<div id='res'></div>
目前,历史实施看起来很混乱,难以阅读。您可以尝试将历史存储与主逻辑分开,如下所示。感觉很好读。 :)
var store = {
keyCount:0,
commandCount:0,
prevCommand:[],
put : function(val) {
this.commandCount++;
this.keyCount = this.commandCount;
this.prevCommand.push(val);
},
get : function() {
this.keyCount--;
if(typeof this.prevCommand[this.keyCount] !== "undefined") {
return this.prevCommand[this.keyCount];
}
}
}
$("#form-prompt").on("submit", function (e) {
store.put($('#textTest').val())
e.preventDefault();
$('#textTest').val('');
});
$(document).keydown(function(event){
if(event.which == 38 && $("#textTest").is(":focus")){
var val = store.get();
val && $('#res').append('<hr>'+val);
}else if(event.which == 40 && $("#command-text").is(":focus")) {
}
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<form id='form-prompt'>
<input type='text' id='textTest'>
<input type="submit" />
</form>
<div id='res'></div>