Javascript 递增事件侦听器事件以侦听特定id(卡1、卡2、卡3等)
问题 我正在制作幻灯片。当我移动到下一张幻灯片时,我会增加我的卡id,如下所示:Javascript 递增事件侦听器事件以侦听特定id(卡1、卡2、卡3等),javascript,jquery,html,Javascript,Jquery,Html,问题 我正在制作幻灯片。当我移动到下一张幻灯片时,我会增加我的卡id,如下所示: cardId++; $('#card-' + (cardId)).show(); 我还有另一个关于键控监听器。。。我想触发一个函数,当有人用“空白输入”类在输入字段中输入文本时,该输入位于具有卡id(卡1、卡2、卡3等)的div中 我的代码: 标记(我正在从数据库循环我的卡片) 将ID更改为类,从循环中删除事件: $('.card-container').on('keyup', '.blank-input',
cardId++;
$('#card-' + (cardId)).show();
我还有另一个关于键控监听器。。。我想触发一个函数,当有人用“空白输入”类在输入字段中输入文本时,该输入位于具有卡id(卡1、卡2、卡3等)的div中
我的代码:
标记(我正在从数据库循环我的卡片)
将ID更改为类,从循环中删除事件:
$('.card-container').on('keyup', '.blank-input', function(){
this.style.width = ((this.value.length + 1) * 12) + 'px';
if ($(this).val() == $(this).attr('data')) {
$(this).removeClass('blank-incorrect').addClass('blank-correct animated tada');
} else {
$(this).removeClass('blank-correct').addClass('blank-incorrect');
}
});
注意:在提供的HTML中不存在空白类,因此HTML的附加将不起作用,为它选择一个不同的选择器
可以添加HTML代码吗?如果可能的话,添加fildder也编辑了我的OP,我正在通过php回显大量数据。。。对于我循环使用的每一张卡,我都会添加一个新的div,其中包含下一个卡id、卡-1、卡-2等。只需创建一个类,并将keyup事件绑定到该类,您的卡-??
元素是动态创建的,还是在加载文档后它们就在那里了?嗨,ibraham,下面的答案解决了我的问题,我的事情太复杂了!我将HTML存储在一个数据库中,这样它就可以在页面加载中。。。无论如何,谢谢你用这么简单的方法解决这个问题!
$(function(){
if (window.location.hash == '') {
var cardId = 1;
} else {
var cardId = parseInt(window.location.hash.substring(1));
}
showCard(); // first thing that is run
/**
* first function to run
*/
function showCard(){
$('#card-' + (cardId)).show();
}
$('#nextCard').click(function(){
if ($('#card-' + (cardId + 1)).length != 0) { // if there is a next card
$('#card-' + (cardId)).hide(); // hide current card
cardId++; // increment the card id
$('#card-' + (cardId)).show(); // and show the next card
location.hash = cardId;
}
});
$('#previousCard').click(function(){
if (cardId != 1) { // if we are not at the first card
$('#card-' + (cardId)).hide(); // hide the current card
cardId--; // decrement the card id
$('#card-' + (cardId)).show(); // and show the previous card
location.hash = cardId;
}
});
/**
* fill in the blank
*/
blanks = document.getElementsByClassName('blank');
for(i = 0; i < blanks.length; i++){
$(blanks[i]).html(
'<input class="blank-input" data="' + $(blanks[i]).html() + '"></input>'
);
}
$('#card-' + (cardId)).on('keyup', '.blank-input', function(){
this.style.width = ((this.value.length + 1) * 12) + 'px';
if ($(this).val() == $(this).attr('data')) {
$(this).removeClass('blank-incorrect').addClass('blank-correct animated tada');
} else {
$(this).removeClass('blank-correct').addClass('blank-incorrect');
}
});
});
$('.card-container').on('keyup', '.blank-input', function(){
this.style.width = ((this.value.length + 1) * 12) + 'px';
if ($(this).val() == $(this).attr('data')) {
$(this).removeClass('blank-incorrect').addClass('blank-correct animated tada');
} else {
$(this).removeClass('blank-correct').addClass('blank-incorrect');
}
});