用js更改字符代码并显示新字符

changing character code with js and show the new character instead

本文关键字:字符 新字符 显示 代码 js      更新时间:2023-09-26

我想写一个代码,如果用户按下某个键,它会更改user事件的keyCode或charCode,并用新的charCode 触发该事件

我用jsfiddle编写了这段代码,但由于递归太多,这段代码不起作用。

function convert(e, elem) {
    function getKey(event) {
        if (event.which == null) {
            return event.keyCode // IE
        } else if (event.which != 0 && event.charCode != 0) {
            return event.which // the rest
        } else {
            return null // special key
        }
    }
    var key = getKey(e);
    key++;
    return key;
}
$(".myInput").keypress(function (e) {
    var returnedKey = convert(e, this);
    e.which = e.keyCode = returnedKey;
    $(this).trigger(e);
});
<input type="text" class="myInput" />

任何有助于我的代码工作的想法都将不胜感激。

非常感谢。

关于递归问题,您需要添加一个停止条件,例如:

$(".myInput").keypress(function (e) {
  var returnedKey = convert(e, this);
   e.which = e.keyCode = returnedKey;
if(!e.isSecondTrigger){
    e.isSecondTrigger = true;
    $(this).trigger(e);
}});

这样,您只需更改一次值。然而,正如LShetty在评论部分所说,事件值是只读的——你不能更改已经按下的按钮的值,这样就可以更改输入文本。为此,您需要在每次用户操作后手动更改输入文本的值(即,在每次按键时保持输入文本的数值,在用户按键时对其进行修改,然后用输出覆盖输入字段值)。