Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
556 views
in Technique[技术] by (71.8m points)

javascript - onChange function is not defined

This has got to be something simple. I searched the internet and only found syntax errors as the cause of this problem, but I can't find a syntax error.

Here's the javascript :

<script type="text/javascript" src="http://localhost/acrilart/javascript/jquery-1.6.4.min.js"></script>
<script type="text/javascript">
    $(document).ready(function(){
        function hi(){
            alert('hi');
        }
        hi();
    });
</script>

And the HTML :

<input type="text" name="cep" value="" id="cep" class="required cep field"
       onChange="hi()" />

On pageload the function hi is called as expected, but my onChange event causes a Firebug error, saying the function is not defined. I'm really stumped. Did I mispell 'hi'?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

The hi function is only in scope inside the ready event handler. Move it outside of the event handler, or handle the binding inside there (and remove the inline event handler attribute from the markup):

$(document).ready(function(){
    function hi(){
        alert('hi');
    }
    $("#cep").on("change", hi);
});

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...