如何在JavaScript中模拟点击事件

时间:2016-06-20 17:55:37

标签: javascript

我创建了一个KeyboardEvent,其中ctrlKey设置为true,而代码是S键,然后尝试运行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>

1 个答案:

答案 0 :(得分:-1)

使用Clients.GroupBy(client => client.Id, client => client) .Select(times => times.OrderBy(client => client.FromDate).First()) 属性:http://codepen.io/topheman/pen/yJaGWv?editors=1001

code