字符插入错误的字符串索引

Characters inserting in wrong index of the string

本文关键字:字符串 索引 错误 插入 字符      更新时间:2023-09-26

我正在尝试在一个特定的字符串中插入额外的字符。

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 ; }           
}
<input id="txt" type="text" placeholder="onkeypress" onkeypress="sample(this)" value="" /><br />
<input id="txt1" type="text" placeholder="onchange" onchange="sample(this)" value="" />

通过在htmlinput中使用onchange属性,代码可以完美运行。但这也可以运行与onkeypress属性吗?如果输入值为1006,则结果应为10'06 "。的帮助。谢谢。

试试这个:

您需要在操作字符串之前替换quotes('/")。也使用keyup事件。参考这个来理解每个事件的目的。 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;
  }
}
<input id="txt" type="text" placeholder="onkeypress" onkeyup="sample(this)" value="" />
<br/>
<input id="txt1" type="text" placeholder="onchange" onchange="sample(this)" value="" />

我知道这个问题已经得到了正确的回答,但这是我的看法。

在格式化函数中添加超时会让用户有机会在格式化开始之前输入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

onchange和onkeypress的区别是,

    当控制从元素释放时,
  1. onchange检测长度和值的变化。
  2. onkeypress检测按下键时长度的变化,但在另一次按下键时值的变化。长度从0开始,这意味着如果我输入4567,而输入7,长度是0,1,2,3,但值是456,即使输入中存在7。但是当你按8时,它显示4567。

你可以在这里看到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 ; }           
		}
<input id="txt" type="text" placeholder="onkeypress" onkeypress="sampleKeyPress(this)" value="" /><br />
<input id="txt1" type="text" placeholder="onchange" onchange="sample(this)" value="" />