开发者

javascript: problem with function

I have this simple function:

<script type="text/javascript">
//<![CDATA[
    jQuery(function($){
        function here(b){alert(b);} ;
        here(6);
    });
//]]>
</scrip开发者_运维百科t>

and i have this button on page:

<button onclick="here(7);">TEST</button>

The alert fires on page load, but not on button click. If i replace the here(7) with alert, it works fine. Why doesnt it work with function though?

Alan


Because your function is defined within a function, it has a limited scope. To access the function globally, you must define it globally. But, this is not recommended. This is why you use libraries like jQuery, to avoid all the globals and to keep things unobtrusive. The best solution for you would be to change the markup to this...

<button id="myBtn">TEST</button> 

And then assign the click handler programmatically in the same area as your defined function...

<script type="text/javascript"> 
//<![CDATA[ 
    jQuery(function($) { 
        function here(b) { alert(b); };    
        here(6); 

        $("#myBtn").click(function() {
          here(7);
        });
    }); 
//]]> 
</script> 

Behavioral separation is much better, wouldn't you say?


You are defining the function here inside another function (see closures). This means that the function here is only available inside the scope of jQuery(function($){

Try:

<script type="text/javascript">
//<![CDATA[
    function here(b){alert(b);} ;
    jQuery(function($){
        here(6);
    });
//]]>
</script>
0

上一篇:

下一篇:

精彩评论

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

最新问答

问答排行榜