use*_*368 7 javascript keyevent
我需要在输入框中触发或说dispatchEvent KeyPress,我已经尝试了很多“ initKeyboardEvent ”,“ initKeyEvent ”,“ createEvent ”,即使我找到了类似问题的答案,但似乎没有任何效果,无论是在firefox中还是在chrome中(我认为它们可能已被弃用),因为 KeyboardEvent.initKeyEvent()已被弃用。
就像我们一样
document.getElemntByID('button').click();
Run Code Online (Sandbox Code Playgroud)
我想做类似的事情:
document.getElemntById('email').keyPress(charCode('a'));
Run Code Online (Sandbox Code Playgroud)
但不幸的是我无法以任何方式使按键工作。
我知道这在 jQuery 中是可能的,但我想用纯 javascript 来做,毕竟 jquery 在后端使用 Javascript,所以如果我没记错的话,一定有办法。
===更新=========
我想知道
window.addEventListener('keydown', keyDown(), true);
function keyDown(){
alert('keydown');
}
var fireOnThis = document.getElementById('pwph');
if( window.KeyEvent ) {
var evObj = document.createEvent('KeyEvents');
evObj.initKeyEvent( 'keydown', true, true, window, false, false, false, false, 72, 0 );
} else {
var evObj = document.createEvent('UIEvents');
evObj.initUIEvent( 'keydown', true, true, window, 1 );
evObj.keyCode = 72;
}
fireOnThis.dispatchEvent(evObj);
Run Code Online (Sandbox Code Playgroud)
此代码返回 true ,甚至 eventListner 正在捕获此事件,那么为什么我看不到输入框中的任何文本?====================更新==============================
这个似乎对每个人都有效,但为什么即使在返回 true 之后,它也会使我的文本字段为空?
// Create the event
var evt = document.createEvent( 'KeyboardEvent' );
// Init the options
evt.initKeyEvent(
"keypress", // the kind of event
true, // boolean "can it bubble?"
true, // boolean "can it be cancelled?"
null, // specifies the view context (usually window or null)
false, // boolean "Ctrl key?"
false, // boolean "Alt key?"
false, // Boolean "Shift key?"
false, // Boolean "Meta key?"
9, // the keyCode
0); // the charCode
// Dispatch the event on the element
el.dispatchEvent( evt );
Run Code Online (Sandbox Code Playgroud)
我试图在 Input 元素内调度 keyPress 事件来传递数据绑定条件(KnockOut js)事件,但不幸的是 KeyPress 对我不起作用,而是我使用更改事件代替它。
所以我这样做了:
element = document.getElementById('idTxtBx_SAOTCS_ProofConfirmation');
element.value = '8885'; // this alone was not working as keypress.
var evt = document.createEvent("HTMLEvents");
evt.initEvent("change", false, true); // adding this created a magic and passes it as if keypressed
element.dispatchEvent(evt);
Run Code Online (Sandbox Code Playgroud)
所以.value和change事件一起制作,假的inputText或按键事件成功。
| 归档时间: |
|
| 查看次数: |
22521 次 |
| 最近记录: |