我试图在特定字符串中插入其他字符。在字符串的错误索引中插入字符
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''。帮帮我。谢谢。
这很奇怪。对于我的代码片段,只有“onkeypress”输入有效。 “onchange”输入不起作用。我正在使用firefox – Magus
@Magus你看过onkeypress的输出吗?它是10'0'6而不是10'06''。另一方面,onchange类似于onblur属性。它只在焦点更改时触发JavaScript代码。 – eirishainjel
@RayonDabre所以它不会在'onkeypress'上工作? – eirishainjel