2013-08-29 42 views
9

你能告诉我如何在同一时间替换下划线的空间(当我在输入字段中输入文本时)? 如果我有我喜欢的字符串。如何将空格替换为下划线(当我在输入字段中输入文本时)?

replace(/ /g,"_"); 

但是我正在寻找,当用户输入的输入栏文本,然后它会自动替换空间下划线。我使用keyup事件只触发第一次。

$("#test").keyup(function() { 
    var textValue = $(this).val(); 
    if(textValue==' '){ 
     alert("hh"); 
    } 
}); 
+0

首先更好地利用KEYDOWN的。 –

+0

我在类似的情况下把它放在HTML为“onKeyDown ='foo();'” –

回答

12

DEMO

$("#test").keyup(function() { 
    var textValue = $(this).val(); 
    textValue =textValue.replace(/ /g,"_"); 
    $(this).val(textValue); 
}); 

更新

DEMO

$("#test").keyup(function() { 
    this.value = this.value.replace(/ /g, "_"); 
}); 
+1

这是比测试哪个按键更好的方法。开销是最小的 –

+0

可以任何身体解决我的这个问题也.http://stackoverflow.com/questions/18502449/why-data-position-fixed-data-tap-toggle-false-not-work/18502566?noredirect = 1#comment27204600_18502566 – Rohit

+0

@tushar请检查这个问题也解决此问题http://stackoverflow.com/questions/18502449/why-data-position-fixed-data-tap-toggle-false-not-work/18502566?noredirect=1 #comment27204600_18502566 – Rohit

0

您可以检测通过添加参数回调哪个键被按下(比方说e),然后测试它的which属性(从documentation

$("#test").keyup(function(e) { 
    if(e.which === 32 /*space*/){ 
     alert("hh"); 
    } 
}); 
+0

请帮忙解决这个问题http://stackoverflow.com/questions/18502449/why-data-position-fixed-data- tap-toggle-false-not-work/18502566?noredirect = 1#comment27204600_18502566 – Rohit

0

您可以用.split( ' ')。加入替换事件的整个价值(' _'); 它比替换更快。

所以,

$("#test").keyup(function() { 
    $(this).val($(this).val().split(' ').join('_')); 
}); 
1

试试这个demo

代码

$("#test").keyup(function(e) { 
    (/ /i).test(this.value)?this.value = this.value.replace(/ /ig,'_'):null; 
}); 
0
$("#test").keypress(function(e) { 
    var textValue = $(this).val(); 
    if(e.keyCode === 32){ 
     $("#test").val(textValue + "_"); 
     return false; 
    } 
}); 
+0

请帮助在这个问题http://stackoverflow.com/questions/18502449/why-data-position-fixed-data-tap-toggle-false-not-work/18502566?noredirect=1#comment27204600_18502566 – Rohit

3

只要试试这个Demo

$("#test").keyup(function() { 
    if ($(this).val().match(/[ ]/g, "") != null) { 
     $(this).val($(this).val().replace(/[ ]/g, "_")); 
    } 
}); 
+1

恕我直言,这是更好比接受的答案。 –

0

小提琴:http://jsfiddle.net/FTmg9/

$(function(){ 
    $('#test').keydown(function(){ 
     $(this).val($(this).val().replace(/\s/g, "_")); 
    }); 
}); 
相关问题