我正在尝试在特定字符串中插入其他字符。
function sample(x) {
if (x.value.length > 2 && x.value.length < 5) {
var first = x.value.substring(0, 2) + "'";
var second = x.value.substring(2, x.value.length) + "''";
x.value = first + "" + second ; }
}
&#13;
<input id="txt" type="text" placeholder="onkeypress" onkeypress="sample(this)" value="" /><br />
<input id="txt1" type="text" placeholder="onchange" onchange="sample(this)" value="" />
&#13;
通过在htmlinput中使用onchange
属性,代码运行完美。但是这也可以使用onkeypress
属性运行吗?如果输入值为1006,则结果应为10&#39;&#39;&#39;&#39;救命。感谢。
答案 0 :(得分:3)
试试这个:
您需要在操作字符串之前替换
quotes('/")
。还可以使用keyup
事件。请参阅this以了解每个事件的目的。密钥发布时会触发onkeyup
function sample(x) {
x.value = x.value.replace(/[\'\"]/g, '');
if (x.value.length > 2 && x.value.length < 5) {
var first = x.value.substring(0, 2) + "'";
var second = x.value.substring(2, x.value.length) + "''";
x.value = first + "" + second;
}
}
&#13;
<input id="txt" type="text" placeholder="onkeypress" onkeyup="sample(this)" value="" />
<br/>
<input id="txt1" type="text" placeholder="onchange" onchange="sample(this)" value="" />
&#13;
答案 1 :(得分:2)
我看到这已经得到了正确的答案,但这是我的看法。
在格式化功能中添加超时会让用户有机会在格式化之前输入4个字符,并可能会让用户感到困惑:
function sample(x) {
setTimeout(function() {
if (x.value.length > 2 && x.value.length < 5) {
var first = x.value.substring(0, 2) + "'";
var second = x.value.substring(2, x.value.length) + "\"";
x.value = first + second;
}
}, 1500); // this is the timeout value in milliseconds
}
请参阅此CodePen以获取一个工作示例: http://codepen.io/Tiketti/pen/YyVRwb?editors=101
答案 2 :(得分:1)
onchange和onkeypress之间的区别是,
您可以在此处看到http://codepen.io/anon/pen/XmRydE
function sample(x) {
console.log(x.value);
console.log(x.value.length);
if (x.value.length > 2 && x.value.length < 5) {
var first = x.value.substring(0, 2) + "'";
var second = x.value.substring(2, x.value.length) + "''";
x.value = first + "" + second ; }
}
function sampleKeyPress(x) {
console.log(x.value);
console.log(x.value.length);
if (x.value.length >= 4 && x.value.length < 5) {
var first = x.value.substring(0, 2) + "'";
var second = x.value.substring(2, x.value.length) + "''";
x.value = first + "" + second ; }
}
&#13;
<input id="txt" type="text" placeholder="onkeypress" onkeypress="sampleKeyPress(this)" value="" /><br />
<input id="txt1" type="text" placeholder="onchange" onchange="sample(this)" value="" />
&#13;