在 keyup 上将 space ' ' 替换为 '-'
Replace space ' ' by '-' on keyup
你好,我有两个输入,当我在第一个输入中写入时,使用 keyup jquery 功能我在第二个输入字段中自动写入。
但是当我单击 space 栏时,我想在第二个输入字段中写行而不是 space。
例如:
First input: Hello world,
Second input: Hello-world
我有以下代码:
$(".firstInput").keyup(function(e) {
val = $(this).val();
if( e.keyCode == 32 ) {
val += "-";
}
$(".secondInput").val( val );
});
只需使用 replace
即可完成,例如:
$(".secondInput").val( $(this).val().replace(/ /g, "-") );
注意: 我建议使用 input
而不是 keyup
,因为它在跟踪用户输入时效率更高。
希望对您有所帮助。
$(".firstInput").on('input', function(e) {
$(".secondInput").val( $(this).val().replace(/ /g, "-") );
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<input class='firstInput' />
<input class='secondInput' />
$(".firstInput").keyup(function(e) {
val = $(this).val();
val = val.replace(/\s/g, '-');
$(".secondInput").val( val );
});
Zakaria Acharki 一行是代码量最少的..但对于初学者来说可能很难掌握。这是初学者更容易遵循的替代方法:
$(".firstInput").keyup(function(e) {
//grab the text, note the use of the var keyword to prevent messing with the global scope
var input1 = $(this).val();
// break the string into an array by splitting on the ' '. Then join the array into a string again with '-' as the glue
input1 = input1.split(' ').join('-');
// or use regex, but regex is a whole other language: input1 = input1.replace(/ /g, "-")
//finally place the modified string into its destination
$(".secondInput").val( input1 );
});
你好,我有两个输入,当我在第一个输入中写入时,使用 keyup jquery 功能我在第二个输入字段中自动写入。
但是当我单击 space 栏时,我想在第二个输入字段中写行而不是 space。
例如:
First input: Hello world,
Second input: Hello-world
我有以下代码:
$(".firstInput").keyup(function(e) {
val = $(this).val();
if( e.keyCode == 32 ) {
val += "-";
}
$(".secondInput").val( val );
});
只需使用 replace
即可完成,例如:
$(".secondInput").val( $(this).val().replace(/ /g, "-") );
注意: 我建议使用 input
而不是 keyup
,因为它在跟踪用户输入时效率更高。
希望对您有所帮助。
$(".firstInput").on('input', function(e) {
$(".secondInput").val( $(this).val().replace(/ /g, "-") );
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<input class='firstInput' />
<input class='secondInput' />
$(".firstInput").keyup(function(e) {
val = $(this).val();
val = val.replace(/\s/g, '-');
$(".secondInput").val( val );
});
Zakaria Acharki 一行是代码量最少的..但对于初学者来说可能很难掌握。这是初学者更容易遵循的替代方法:
$(".firstInput").keyup(function(e) {
//grab the text, note the use of the var keyword to prevent messing with the global scope
var input1 = $(this).val();
// break the string into an array by splitting on the ' '. Then join the array into a string again with '-' as the glue
input1 = input1.split(' ').join('-');
// or use regex, but regex is a whole other language: input1 = input1.replace(/ /g, "-")
//finally place the modified string into its destination
$(".secondInput").val( input1 );
});