开发者

jQuery issue with Propagation and Keydown

I had gotten help earlier here with what turned out to be a propagation issue, but I am now trying to use HTML5 autofocus on an input and now my code breaks.

Here's the code I'm working with:

<script type="text/javascript">
var $j = jQuery.noConflict();

$j(':not(form)').keydown(function(event) {

    $j('form').keydown(function(event) {
        event.stopPropagation();
    });

    if(event.keyCode==82) {
        $j(document).trigger(location.href = '/?random')
    }
});
</script>

Basically, I have some keyboard navigation set up. If you press R, it takes you to a random page.

I was trying to disable that functionality when a user was typing in a form/input box, for obvious reasons. This code works, EXCEPT when I try to use autofocus. If you start typing right on the pageload, and the first letter you type is R, it goes to a random page.

If another letter is typed firs开发者_JAVA百科t, then R gets entered as a normal letter. I'm kind of a newbie at this stuff, so any help is much appreciated! Thanks.

EDIT: Upon further testing, it appears the issue might not be the autofocus, but mainly that just when the first letter typed is an R, it bugs out.


your selector with "not" was not correct.

<script type="text/javascript">

$(document).ready(function(){
    $('body').keydown(function(event) {
        if(event.keyCode==82) {
            $(document).trigger(location.href = '/?random')
        }
    });
    $('input, textarea').keydown(function(){
        event.stopPropagation();
    });
});
</script>


The thing is that you're adding a keydown event to the form element every time keydown is called on any other element.

Try this out.. I changed your JS a bit...

http://jsfiddle.net/CAjNR/1/

Here's the code from the fiddle:

HTML:

<form>
    <input type="text" autofocus />
    <input type="text" />
    <input type="text" />
    <input type="text" />
    <textarea></textarea>
    <div id="results">
    </div>
</form>

JS

var $j = jQuery.noConflict();

$j(document).keydown(function(event) {
    var key = event.keyCode | event.which;
    if(key==82) {
        $j('#results').append($j('<div>pressed: r</div>'));
    }
});
$j('input, textarea').keydown(function(event) {
   event.stopPropagation(); 
});
0

上一篇:

下一篇:

精彩评论

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

最新问答

问答排行榜