var maxLength = 4;
e = jQuery.Event("keypress")
e.which = 13
$('#input').on('input focus keydown keyup', function() {
var text = $(this).val();
var lines = text.split(/(\r\n|\n|\r)/gm);
for (var i = 0; i < lines.length; i++) {
if (lines[i].length > maxLength) {
lines[i] = lines[i].substring(0, maxLength);
//lines[i] = lines[i];
}
}
$(this).val(lines.join(''));
});
每个4号码值后应该转到下一行我申请此代码不起作用请指导
答案 0 :(得分:0)
您需要确保输入没有任何换行符,然后再按块分隔它们
$('#mytext').on('input', function() {
var value = $(this).val().split( "\n" ).join( "" );
var output = getChunks( value, 4 );
$(this).val(output.join("\n"));
});
function getChunks(str, chunk) {
var i, j;
var output = [];
var array = str.split( "" );
for (i = 0, j = array.length; i < j; i += chunk)
{
output.push( array.slice(i, i + chunk).join( "" ) );
}
return output;
}
<强>演示强>
$('#mytext').on('keydown', function(e) {
if (e.which == 13 )
{
e.preventDefault();
alert( "Enter was pressed" );
this.blur();
return false;
}
});
$('#mytext').on('input', function() {
var value = $(this).val().split( "\n" ).join( "" );
var output = getChunks( value, 4 );
$(this).val(output.join("\n"));
});
function getChunks(str, chunk) {
var i, j;
var output = [];
var array = str.split( "" );
for (i = 0, j = array.length; i < j; i += chunk)
{
output.push( array.slice(i, i + chunk).join( "" ) );
}
return output;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<textarea id="mytext" name="text_body"></textarea>