如何在JavaScript中模拟点击事件

如何在JavaScript中模拟点击事件,javascript,Javascript,我创建了一个KeyboardEvent,将ctrlKey设置为true,并将S键的代码设置为true,然后尝试运行document。dispatchEvent(e)尝试模拟ctrl+S快捷方式,但事件侦听器似乎没有发现这一点。有没有其他方法来模拟这个事件 <!DOCTYPE html> <html> <head> <title></title> <script type="text/javascript">

我创建了一个
KeyboardEvent
,将
ctrlKey
设置为true,并将S键的代码设置为true,然后尝试运行
document。dispatchEvent(e)
尝试模拟
ctrl+S
快捷方式,但事件侦听器似乎没有发现这一点。有没有其他方法来模拟这个事件

<!DOCTYPE html>
<html>
<head>
    <title></title>
    <script type="text/javascript">
        document.addEventListener("keydown", function (event) { console.log(event.which); });

        onkeydown = function (e) {
            if (e.ctrlKey && (e.which == 'S'.charCodeAt(0) || e.which == 's'.charCodeAt(0))) {
                e.preventDefault();
                alert("CTRL + S was pressed")
            }
        }

        function buttonClick() {
            var e = new KeyboardEvent("event", { 'ctrlKey': true, 'which': 83 });
            document.dispatchEvent(e);
        }
    </script>
</head>
<body>
    <form id="form1" runat="server">
        <div>
            <button ID="Button1" onclick="buttonClick();">Test</button>
        </div>
    </form>
</body>
</html>

addEventListener(“keydown”,函数(事件){console.log(event.which);});
onkeydown=函数(e){
if(e.ctrlKey&(e.which='S.charCodeAt(0)| | e.which='S.charCodeAt(0))){
e、 预防默认值();
警报(“按下CTRL+S”)
}
}
函数按钮单击(){
var e=新键盘事件(“事件”,{'ctrlKey':true,'which':83});
文件。调度事件(e);
}
试验

使用
code
属性:


addEventListener(“keydown”,函数(事件){console.log(event.code,event.ctrlKey);});
函数按钮单击(){
var e=newkeyboardevent(“keydown”,{'ctrlKey':true,'which':83,'code':83});
文件。调度事件(e);
}
试验

您是在项目中使用jQuery还是纯JavaScript?首选纯JavaScript,如警告所示。到底出了什么问题?我指的是事件侦听器本身没有从按钮
onclick
event拾取模拟。应该在
console.log()中显示
keydown
事件code
<script type="text/javascript">

        document.addEventListener("keydown", function (event) { console.log(event.code, event.ctrlKey); });

        function buttonClick() {
            var e = new KeyboardEvent("keydown", { 'ctrlKey': true, 'which': 83, 'code': 83 });
            document.dispatchEvent(e);
        }
</script>
<form id="form1" runat="server">
  <div>
    <button ID="Button1" onclick="buttonClick();">Test</button>
  </div>
</form>