开发者

events not firing for "input" in chrome jquery

开发者 https://www.devze.com 2023-04-11 06:21 出处:网络
I can\'t get any key events to fire on an input element with jquery.Given the foll开发者_运维知识库owing code:

I can't get any key events to fire on an input element with jquery. Given the foll开发者_运维知识库owing code:

<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.0 Transitional//EN">
<html>
    <head>
        <script type="text/javascript" src="./js/jquery-1.5.1.min.js"></script>
        <script type="text/javascript" src="./js/jquery-ui-1.8.14.custom.min.js"></script>
        <script type="text/javascript">         


            $("#cmd").keypress(function(event) {
                alert("keypress");
                if(event.which == 13){
                    $.ajax({
                        type: "POST",
                        url: "update",
                        data: "key=" + key + "&cmd=" + $("#cmd").val()
                    });
                    $("#cmd").val("");
                    $("#cmd").focus();
                }
            });


    </script>
        <title>BCMD</title>
    </head>
    <body>
        <div id="main" style="background-color: black; color: white; width:100%; height:500px;">
            <input id="cmd" type="text" style="border:0;"></input>
        </div>
    </body>
</html>

Nothing is firing. Any ideas? Thanks.


You're missing the $(document).ready function. Enscapsulate your Javascript in $(function() {} ); to get it to work.

    <script type="text/javascript">         

        $(function() {
            $("#cmd").keypress(function(event) {
                alert("keypress");
                if(event.which == 13){
                    $.ajax({
                        type: "POST",
                        url: "update",
                        data: "key=" + key + "&cmd=" + $("#cmd").val()
                    });
                    $("#cmd").val("");
                    $("#cmd").focus();
                }
            });
        });

</script>

JQuery requires this kind of code to be encapsulated like that to indicate it should only be run when the document has loaded.


You are executing the code before the cmd element exists. Wrap your code in document.ready:

$(function(){
    // your code here
})

This will wait until the DOM has loaded before executing your code.

0

精彩评论

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