![](/img/trans.png)
[英]jQuery bind event on dynamic element for focus, keypress, keydown, keyup didn't work
[英]focus on element and then cause a keydown or keyup space event
我目前正在使用Chrome最新版本。 我有以下簡單的html代碼:
<!DOCTYPE html>
<html>
<head>
</head>
<body>
<html>
<input id="inputfield" type = "textfield">
</html>
</body>
</html>
然后使用javascript,我首先嘗試設置確定字段的文本,然后將其聚焦,然后按下空格鍵。
textbox = document.getElementById("inputfield")
textbox.value = "word";
var evt = document.createEvent("KeyboardEvent");
evt.initKeyboardEvent(
"keyup",
true,
true,
window,
false,
false,
false,
false,
32,
0
);
textbox.focus();
textbox.dispatchEvent(evt);
但是沒有焦點發生,最后一行只是返回true; 我正在通過Chrome控制台執行代碼,我不知道這是否會有所作為。
謝謝
您的標記不正確, html
標記未出現在正文中。
應該是這樣的:
<!DOCTYPE html>
<html>
<head>
</head>
<body>
<input id="inputfield" type = "textfield">
</body>
</html>
然后,就像@FAngel所說的那樣,您不能以這種方式更改輸入字段的值,必須將其文本設置為所需的任何值。
您只需觸發一個事件。 但是它不會更改值,“單詞”也不會變成“單詞”。 不知道為什么它不能從控制台運行,但是可能是您缺少重要的東西。 可能是因為var(我已經幾次注意到這個問題了)。 嘗試更改var evt = document.createEvent("KeyboardEvent");
簡單地evt = document.createEvent("KeyboardEvent");
。
我在Firefox 12.0上收到“ TypeError:evt.initKeyboardEvent不是函數”
這是因為在Firefox中,該函數稱為initKeyEvent。 這是一個支持firefox和google chrome的代碼:
textbox = document.getElementById("inputfield")
textbox.value = "word";
var evt = document.createEvent("KeyboardEvent");
var keyEventFunction = (evt.initKeyboardEvent ? "initKeyboardEvent" : "initKeyEvent");
evt[keyEventFunction](
"keyup",
true,
true,
window,
false,
false,
false,
false,
32,
0
);
textbox.focus();
textbox.dispatchEvent(evt);
和演示: http : //jsfiddle.net/Y674s/2/
UPD:
當您在控制台中運行代碼時,焦點設置為您的字段,但是您只能看到它。 要看到這一點,請像這樣修改您的輸入HTML:
<input id="inputfield" type = "textfield" onblur="alert('focus was in textfield')">
onblur事件僅在某些領域被聚焦但后來的焦點轉移到其他地方的情況下才發生。 現在,在控制台中運行代碼,然后單擊頁面正文中的某個位置。 您將看到該警報出現。 如果僅打開頁面而不運行該代碼,則不會出現aler。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.