问题
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