字符插入错误的字符串索引
Characters inserting in wrong index of the string
我正在尝试在一个特定的字符串中插入额外的字符。
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的区别是,
- 当控制从元素释放时,
- onchange检测长度和值的变化。
- 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="" />
相关文章:
- AngularJS-ng使用字符串索引在数组上重复
- 在 JavaScript 中动态创建带有字符串索引的二维表
- 按字符串索引的 Javascript 数组
- 按字符串索引访问字典对象
- 每个和字符串索引
- 使用字符串中的开始和结束单词以及 javascript 中的子字符串索引查找子字符串
- JavaScript 数组中的字符串索引
- 如何从数组中删除特定元素?与字符串索引
- Why for var在数组中返回一个字符串索引
- 为什么数组中的字符串索引不会增加'长度'
- 字符插入错误的字符串索引
- Javascript字符串索引
- 如何在不计算扩展实体的情况下找到标记(元素)的字符串索引?
- 如何忽略字符串索引中的空格,并在句子中的每个单词上以大写字母开头
- Jquery的每个函数都不能用于字符串索引数组
- 为什么IE's插入符在文本输入中的位置不等于字符串索引?解决方法是什么?
- 字符串索引器在本地工作,但在网站托管时不起作用
- 在Javascript中迭代由字符串索引的数组
- 在javascript中创建两个数组的字符串索引对象
- 如何创建具有字符串索引的二维对象并循环遍历结果