HTML:
<div class="col-md-10 col-sm-10 col-xs-10">
{{ form_widget(experienceForm.description, {
'attr': {
'class': 'form-control field-max-length field-max-length field-line-length',
'rows': 6
}
})}}
</div>
handleChangeLineCounter = function() {
$('.field-line-length').keyup(function (e) {
e.preventDefault();
var countLineNum = (this.value.match(/\n/g)||[]).length;
console.log(countLineNum);
checkEnterKey ($(this), 7, countLineNum);
});
}
function checkEnterKey (getVarName, maxLine, countLine) {
var msg2 = maxLine - countLine +' lignes restantes,';
if ((maxLine - countLine) === 1 || (maxLine - countLine) === 0) {
msg2 = maxLine - countLine +' ligne restante,';
}
getVarName.keypress(function(e) {
if(e.which === 13) {
if ((maxLine - countLine) < 1) {
return false;
}
else if ((maxLine - countLine) > 0) {
return true;
}
}
});
$('.counter-msg-2').remove();
getVarName.after('<span class="counter-msg-2 m-r-5"><span class="counter_msg_2">' + msg2 + '</span></span>');
}
从上面的代码中,在函数checkEnterKey()
中,当(maxLine - countLine
)达到0时,我按下删除键或退格键,然后再次按回车键,键停止工作。
相反,如果(maxLine - countLine
)没有达到0,我按删除键或退格键再按回车键,键正常工作。
当我到达(maxLine - countLine) = 0
时,如何让回车键生效?
答案 0 :(得分:1)
您的代码存在一些问题:
keypress
添加keyup
的新事件处理程序,这非常糟糕。remove()
和after()
,这比仅仅放置元素和使用html()
更简单。以下解决方案有一些代码清理以及上述问题的补救措施。
// main function for attaching the event handlers to your element
function handleChangeLineCounter(max) {
// initial value for the counter
$('.counter-msg-2').html(`${max} lignes restantes`);
// keypress event to handle only allowing the needed lines
// this code is not part of the keyup event because returning
// false here won't prevent the key from appearing
$('.field-line-length').keypress(function (e) {
let diff = max - ($(this).val().match(/\n/g) || []).length;
if (e.which === 13 && diff === 0) {
return false;
}
});
// keyup event to handle the counter display
// this code is not part of the keypress event because the last
// input key would be missing
$('.field-line-length').keyup(function (e) {
let diff = max - ($(this).val().match(/\n/g) || []).length;
let msg = ((diff <= 1) ? `${diff} ligne restante` : `${diff} lignes restantes`);
$('.counter-msg-2').html(msg);
});
};
handleChangeLineCounter(7);
.field-line-length {
width: 500px;
height: 120px;
overflow-y: scroll;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<textarea class="field-line-length"></textarea>
<span class="counter-msg-2 m-r-5">
<span class="counter_msg_2"></span>
</span>
我希望这会有所帮助。