【发布时间】:2021-01-04 21:29:47
【问题描述】:
尝试使用下面的 sn-p 创建 keydown 事件。 keypress 函数触发,但该值未添加到文本框中。我想使用键编辑文本框 1 的值。
fyi - 故意避免直接设置 element.value
<html>
<head>
<script>
function f1() {
document.querySelector("#text1").focus()
document.querySelector("#text1").onkeydown = test;
var keypress = new KeyboardEvent("keydown", {
key: "e",
keyCode: 69, // example values.
code: "KeyE", // put everything you need in this object.
which: 69,
shiftKey: false, // you don't need to include values
ctrlKey: false, // if you aren't going to use them.
metaKey: false // these are here for example's sake.
})
console.log("srcElement" + keypress.srcElement);
console.log("currentTarget" + keypress.currentTarget);
var element = document.getElementById("text1")
element.dispatchEvent(keypress);
console.log("srcElement" + keypress.srcElement);
console.log("currentTarget" + keypress.currentTarget);
}
function test(e) {
console.log("Called" + e.key);
console.log("Called" + e.keyCode);
}
</script>
</head>
<body onload="f1()">
<form>
Input 1 : <input type="text" id="text1" name="text1" />
Input 2 :<input type="text" id="text2" name="text2" />
</form>
</body>
</html>
这是控制台上的输出:
test.html:17 srcElementnull
test.html:18 currentTargetnull
test.html:25 Callede
test.html:26 Called69
test.html:21 srcElement[object HTMLInputElement]
test.html:22 currentTargetnull
【问题讨论】:
-
没用是什么意思?你得到什么错误?
-
有人在这里问过类似的问题:stackoverflow.com/questions/65558501/…
-
您是否希望这些事件也改变元素的值?因为它不是那样工作的。事件就是事件,值就是 JavaScript 中的值。通过简单地调度一个事件,值不会改变。
标签: javascript