onChange function is not defined

落爺英雄遲暮 提交于 2019-12-18 07:41:18

问题


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'?


回答1:


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);
});



回答2:


The hi function is only defined in the ready block. Outside, it doesn't exist anymore.

You don't need to wrap function definitions in .ready(), so just remove it. Alternatively, define the function like this:

window.hi = function() {...}



回答3:


<script src="http://code.jquery.com/jquery-latest.js"></script>

<script type="text/javascript"> 
function hi(){ 
    alert('hi'); 
} 
</script>

<input type="text" name="cep" value="" id="cep" class="required cep field" onKeyPress="javascript:hi();" />



回答4:


In your code block:

<script type="text/javascript">
    $(document).ready(function(){
        function hi(){
            alert('hi');
        }
        hi();
    });
</script>

hi is not a global function. You can access it only inside the scope of your function(){...}, not from outside.

Since you are using jQuery, you can change the way you bind your function to the onChange event. Rather than calling it from the html tag, you can write:

<script type="text/javascript">
    $(document).ready(function(){
        function hi(){
            alert('hi');
        }
        hi();

        $('#cep').on( 'change', function(){ hi(); } );
    });
</script>



回答5:


onchange is only triggered when the control is blurred. Try onkeypress instead.

$("#cep").on("change", function() {
   alert(1);
});

or

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

Use following events instead of onchange:

- onkeyup(event)
- onkeydown(event)
- onkeypress(event)


来源:https://stackoverflow.com/questions/12621258/onchange-function-is-not-defined

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!