我正在制作一个类似于聊天对话的东西,您可以通过按空格键来下一条消息,但它不起作用,有一个实时代码:
谁能解释一下如何通过按一个键来排序下一条消息的事件吗?
谢谢!
最佳答案
这就是您要找的吗:http://jsfiddle.net/VCpqs/11/ ?
您需要跟踪当前正在显示的消息(我为此使用类 current
),并相应地隐藏该消息并仅显示下一条消息。
这是 jquery:
$(document).keyup(function(event) {
if (event.which === 32) {
if ($('#msg1').hasClass('current'))
{
$('#msg1').hide('slow').removeClass('current');
$('#msg2').show('slow').addClass('current');
}
else if ($('#msg2').hasClass('current'))
{
$('#msg2').hide('slow').removeClass('current');
$('#msg3').show('slow').addClass('current');
}
}
});
很高兴知道你让它在循环中工作。我只是在循环中实现它,这就是我得到的:http://jsfiddle.net/VCpqs/18/
var messages = new Array('msg1','msg2','msg3');
$(document).keyup(function(event) {
if (event.which === 32) {
for (x in messages)
{
if ($('#'+messages[x]).hasClass('current'))
{
$('#'+messages[x]).hide('slow').removeClass('current');
$('#'+messages[(parseInt(x)+1)]).show('slow').addClass('current');
break;
}
}
}
});
关于jquery - 如何使用 jQuery 按键对事件进行排序?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/8722053/