【问题标题】:Replace space ' ' by '-' on keyup在 keyup 上用“-”替换空格“”
【发布时间】:2017-07-02 00:57:12
【问题描述】:
你好,我有两个输入,当我在第一个输入中写入时,使用 keyup jquery 函数我会在第二个输入字段中自动写入。
但是当我单击空格键时,我想在第二个输入字段中写入行而不是空格。
例如:
第一个输入:Hello world,
第二个输入:Hello-world
我有以下代码:
$(".firstInput").keyup(function(e) {
val = $(this).val();
if( e.keyCode == 32 ) {
val += "-";
}
$(".secondInput").val( val );
});
【问题讨论】:
标签:
javascript
jquery
input
keyup
【解决方案1】:
这可以简单地使用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' />
【解决方案2】:
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 );
});
【解决方案3】:
$(".firstInput").keyup(function(e) {
val = $(this).val();
val = val.replace(/\s/g, '-');
$(".secondInput").val( val );
});