它第一次运行顺畅,但是当我重复过程时,它会触发两次添加2个字段而不是每个Shift + Enter一个,是否有人可以解释为什么并提供解决方案?
$(document).on('click', "span.adbt", function () {
$('.caddtask').toggleClass('inactive').html("<span class='tfields'><textarea autofocus placeholder='Shift+Enter adds another field' maxlength='30' class='tinput n1' /></span><span class='add'></span>").css({
'height': '52px'
});
$('.add').click(function () {
SaveTask(date)
});
$(document).on('keypress', "textarea.tinput", function (e) {
if (e.which == 13 && e.shiftKey && $('.tinput:last-of-type').attr('class').slice(-1) < 4) {
e.preventDefault();
$('.tfields').append("<textarea autofocus maxlength='30' class='tinput n" + (Number($('.tinput:last-of-type').attr('class').slice(-1)) + 1) + "' />");
$('.caddtask').css({
'height': '+=44'
});
$('.add').css({
'top': '+=22'
});
}
});
});
function SaveTask(date) {
var fields = $('.tinput:last-of-type').attr('class').slice(-1);
if (Day[date.dayOfYear()].tasks == '') $('.tlist').html('');
for (var i = 1; i <= fields; i++) {
if ($('.n' + i).val() === '') {
$('.tinput').attr('placeholder', 'Enter a task here');
return;
}
if (tasks.length > 0) {
var id = tasks.length;
tasks[id] = {
id: tasks[(id - 1)].id + 1,
belongs: Number(String(2014).slice(2, 4).concat('00'.concat(date.dayOfYear()).slice(-3))),
status: false,
text: $('.n' + i).val()
};
$('.tlist').append("<li class='id" + tasks[id].id + "'><span class='status false'></span><span class='tasktext'>" + tasks[id].text + "</span></li>");
} else {
var id = 0;
tasks[0] = {
id: 0,
belongs: Number(String(2014).slice(2, 4).concat('00'.concat(date.dayOfYear()).slice(-3))),
status: false,
text: $('.tinput').val()
};
$('.tlist').html("<li class='id" + tasks[0].id + "'><span class='status false'></span><span class='tasktext'>" + tasks[0].text + "</span></li>");
}
}
localStorage.setItem('tasks', JSON.stringify(tasks));
$('.caddtask').toggleClass('inactive').html("<span class='adbt'>Add task</span>");
$('.add').css({
'top': '14px'
});
$('.inactive').css({
'height': '26px'
});
};
为什么它会停止自动对焦textearea的第二次执行?
答案 0 :(得分:4)
您的问题
在其他事件处理程序中分配事件处理程序
这将在每次点击span.adbt
时分配事件处理程序
因此,你可以多次执行处理程序,就像你说的那样,你的第二次点击会有两次。
<强>解决方案强>
让您的事件处理程序分开......
应该是:
$(document).on('click', "span.adbt", function () {
$('.caddtask').toggleClass('inactive').html("<span class='tfields'><textarea autofocus placeholder='Shift+Enter adds another field' maxlength='30' class='tinput n1' /></span><span class='add'></span>").css({
'height': '52px'
});
});
$('.add').on('click',function () {
SaveTask(date);
});
$(document).on('keypress', "textarea.tinput", function (e) {
if (e.which == 13 && e.shiftKey && $('.tinput:last-of-type').attr('class').slice(-1) < 4) {
e.preventDefault();
$('.tfields').append("<textarea autofocus maxlength='30' class='tinput n" + (Number($('.tinput:last-of-type').attr('class').slice(-1)) + 1) + "' />");
$('.caddtask').css({
'height': '+=44'
});
$('.add').css({
'top': '+=22'
});
}
});