Trigger backspace key in jQuery

我只是一个虾纸丫 提交于 2020-05-15 08:07:10

问题


How can I trigger the backspace key event in jQuery?

The following example isn't working:

var e = jQuery.Event("backspace", { keyCode: 8 });
$("#myarea").trigger( e );

回答1:


You can't actually trigger it.

You could, for example, remove the last character from a certain input, but you can't trigger the actual key.

Example:

var str = $('#input').val();
$('#input').val(str.substring(0, str.length - 1));



回答2:


You can't trigger the backpace key.

With the jquery caret plugin, you can simulate the press on the backspace key by removing the correct characters.

backspace = function (element_name) {
    var element = $(element_name);
    var caret_pos = element.caret();
    var new_val = element.val().substr(0, caret_pos - 1) + element.val().substr(caret_pos);
    element.val(new_val);
    if (caret_pos > 0) {
        element.caret(caret_pos - 1);
    }
};

See this jsfiddle (you might need to change the caret plugin source)



来源:https://stackoverflow.com/questions/9244677/trigger-backspace-key-in-jquery

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!