js input box limits the number of words in the input box, the following code
<input type='text' onkeyup="checkNumber($(this))">
function checkNumber($this){
let val=$this.val();
if(val.length > 10 ){
alert('字數(shù)超過10');
}
}
During the actual process, the following problems were discovered, as shown in the figure:
In the input method, the letters are displayed first, and then the pinyin of the letters is converted into Chinese characters. Therefore, it may be that when inputting, the number of letters plus Chinese characters exceeds the limited number of characters. How to solve the problem?
擁有18年軟件開發(fā)和IT教學經(jīng)驗。曾任多家上市公司技術總監(jiān)、架構師、項目經(jīng)理、高級軟件工程師等職務。 網(wǎng)絡人氣名人講師,...
We imagine that the input is also in full English or Chinese, and the length needs to be limited to less than 10, then maxlength="10" is required. The checkNumber function then determines whether the input contains Chinese characters, and if so, determines whether the last character is in English. . If there is no Chinese explanation and it is in pure English, it will prompt you. It is difficult to judge the shortcomings of the plan if both Chinese and English exist together.
The following example, I wonder if it will help you
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>input 事件兼容處理以及中文輸入法優(yōu)化</title>
</head>
<body>
<input type='text'>
<script>
var input = document.querySelector('input');
var isLock = false;
//當瀏覽器有非直接的文字輸入時, compositionstart事件會以同步模式觸發(fā).
input.addEventListener('compositionstart', function(){
isLock = true;
})
//當瀏覽器是直接的文字輸入時, compositionend會以同步模式觸發(fā).
input.addEventListener('compositionend', function(){
isLock = false;
});
input.addEventListener('input',function(e){
if(!isLock)console.log(this.value);
});
</script>
</body>
</html>
Replace the onkeyup event with the onblur event to solve the problem.