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

时间:2015-10-07 07:36:36

标签: javascript html

我正在尝试在特定字符串中插入其他字符。



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;
&#13;
&#13;

通过在htmlinput中使用onchange属性,代码运行完美。但是这也可以使用onkeypress属性运行吗?如果输入值为1006,则结果应为10&#39;&#39;&#39;&#39;救命。感谢。

3 个答案:

答案 0 :(得分:3)

试试这个:

  

您需要在操作字符串之前替换quotes('/")。还可以使用keyup事件。请参阅this以了解每个事件的目的。密钥发布时会触发 onkeyup

&#13;
&#13;
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;
&#13;
&#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之间的区别是,

  1. onchange检测从元素
  2. 释放控件时的长度和值的变化
  3. onkeypress检测按键时长度的变化,但在另一次按键时改变值。长度从 0 开始,这意味着如果我输入4567,而输入7,则长度为0,1,2,3但是值为456,即使输入中存在7。但是当你按 8 时,它会显示4567.
  4. 您可以在此处看到http://codepen.io/anon/pen/XmRydE

    &#13;
    &#13;
     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;
    &#13;
    &#13;