开发者

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.

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!

When I press some button, the S in this example, I do get the alert, but the page gets reloaded! Why is the 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.

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.

$('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. If you want the page to reload just remove this line.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜