Why is this function undefined?

2019-03-05 05:01发布

问题:

I was hoping i was past this... but why is is resize undefined on Button click?

    $(document).ready(function(){
    var w = [320, 480];
    var h = [480, 620];

    function resize (input){
        $("scale").width(w[input]);
        $("scale").height(h[input]);
    }

    $.each(w, function(i, val){
        $("<button onclick='resize("+i+")'>"+val+"</button>").appendTo("body");
    }); 
});

回答1:

Because its inside the document.ready function.

You need to have the resize function at the global level for the DOM to see it.

However a better way of doing it would be to use the jQuery "on" function.



回答2:

function resize exists only in the scope of the onReady callback you pass into document.ready ... It needs to exist "higher up" / "more globally" for this to work, or do what @blazemonger mentions, bind it directly instead of using the onclick= html attribute



标签: jquery scope