Trigger a keypress/keydown/keyup event in JS/jQuery?
What is the best way to simulate a user entering text in a text input box in JS and/or jQuery?
I dont want to actually put text in the input box, I just want to trigger all the event handlers that would normally get triggered by a user typing info into a input box. This means focus, keydown, keypress, keyup, and blur. I think.
So how would one accomplish this?
You can trigger any of the events with a direct call to them, like this:
$(function() {
$('item').keydown();
$('item').keypress();
$('item').keyup();
$('item').blur();
});
Does that do what you're trying to do?
You should probably also trigger .focus()
and potentially .change()
If you want to trigger the key-events with specific keys, you can do so like this:
$(function() {
var e = $.Event('keypress');
e.which = 65; // Character 'A'
$('item').trigger(e);
});
There is some interesting discussion of the keypress events here: jQuery Event Keypress: Which key was pressed?, specifically regarding cross-browser compatability with the .which property.
要触发一个输入按键,我必须修改@ebynum响应,特别是使用keyCode属性。
e = $.Event('keyup');
e.keyCode= 13; // enter
$('input').trigger(e);
这是一个香草js例子来触发任何事件:
function triggerEvent(el, type){
if ('createEvent' in document) {
// modern browsers, IE9+
var e = document.createEvent('HTMLEvents');
e.initEvent(type, false, true);
el.dispatchEvent(e);
} else {
// IE 8
var e = document.createEventObject();
e.eventType = type;
el.fireEvent('on'+e.eventType, e);
}
}
链接地址: http://www.djcxy.com/p/17438.html
上一篇: 你发现了什么扩展方法的优点?