简体   繁体   English

如何通过使用javascript的快捷方式单击按钮而不会导致页面重新加载

[英]How to click a button through a shortcut with javascript without causing a page reload

I need some shortcuts in my web application, that will do the same as when a user clicks on a button, or presses the button with the accesskey. 我在Web应用程序中需要一些快捷方式,这些快捷方式的作用与用户单击按钮或使用快捷键按下按钮的方式相同。

I simplified my code to show you my problem: 我简化了代码以向您展示我的问题:

<html>
<head><script src="jquery-1.4.2.js" type="text/javascript"></script></head>
<form>
    <body>
        <div id="myDiv">text</div>
        <input name="cmdChangeText" type="submit" value="change text" onclick="document.getElementById('myDiv').innerText='text is changed'; return false;" />

        <input name="cmdTestButton" type="submit" value="hello" onclick="alert('hello'); return false;" accesskey='z' />
    </body>
</form>
<script type="text/javascript">
    document.onkeydown = function() {
        if (event.keyCode == 83) { //83 = 's'
            window.$('[accesskey=z]').click();
        }
    }
</script>
</html>

The first button changes the text. 第一个按钮更改文本。 When you click the second button, or click it through accesskey ( Alt + Z in IE), you get the alert, but the page does not reload: the text is still changed! 当您单击第二个按钮或通过快捷键(IE中的Alt + Z )单击它时,您会收到警报,但页面不会重新加载:文本仍然更改!

When I press some button, the S in this example, I do get the alert, but the page gets reloaded! 当我按下某个按钮(在本例中为S)时,我确实收到了警报,但是页面已重新加载! Why is the return false; 为什么return false; ignored this way, and what can I do about it? 忽略这种方式,我该怎么办?

I would get rid of the onclick="alert('hello'); return false" stuff and attach events using jQuery. 我会摆脱onclick="alert('hello'); return false"东西,并使用jQuery附加事件。

After that, you can try cancel the event bubbling: 之后,您可以尝试取消事件冒泡:

$('#myInput2').click(
    function() {
        alert('hello')
        return false
    }
 )

Just a hunch. 只是一种预感。

Give the buttons different names, in this example I have used 'test1' and 'test2' and add the following code. 为按钮指定不同的名称,在此示例中,我使用了'test1'和'test2'并添加以下代码。

$('input[name=test1]').click( function(e){
    e.preventDefault();
    $('#myDiv').innerText('text is changed');
});

$('input[name=test2]').click( function(e){
    e.preventDefault();
    alert('hello');
});

An input of type 'submit' will submit the page by default. 默认情况下,类型为“提交”的输入将提交页面。 Using 'preventDefault()' method on the event will, unsurprisingly prevent the default action. 毫无疑问,在事件上使用'preventDefault()'方法将阻止默认操作。 If you want the page to reload just remove this line. 如果重新加载页面,只需删除此行。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM