0
(function () {

    function callbackF(data) {
        eval(data.script);
    }

    window.onload = function () {
        if (url.indexOf('.html') > 0) {
            var gt_widget_id = document.createElement('div');
            gt_widget_id.setAttribute('id', 'gt_widget_0');
            var comments = document.getElementById('comments');
            comments.parentNode.insertBefore(gt_widget_id, comments);
            var comments = document.getElementById('comments');
            var script = document.createElement('script');
            script.setAttribute('src', "http://dev.example.com/wp/wpregister.asp?callback=callbackF&ver=2.5&url=" + encoded_url);
            script.setAttribute("type", "text/javascript");
            script.setAttribute("id", "grazit_script");
            document.getElementById("gt_widget_0").parentNode.appendChild(script);
        }
    }
})();

html与问题无关,标签确实被附加并且json返回就在调用之后,控制台告诉我callbackF未定义?这是为什么?

4

1 回答 1

1

这是为什么?

因为您需要callbackF在闭包之外定义函数:

function callbackF(data) {
    eval(data.script);
}

(function () {
    window.onload = function () {
        if (url.indexOf('.html') > 0) {
            var gt_widget_id = document.createElement('div');
            gt_widget_id.setAttribute('id', 'gt_widget_0');
            var comments = document.getElementById('comments');
            comments.parentNode.insertBefore(gt_widget_id, comments);
            var comments = document.getElementById('comments');
            var script = document.createElement('script');
            script.setAttribute('src', "http://dev.example.com/wp/wpregister.asp?callback=callbackF&ver=2.5&url=" + encoded_url);
            script.setAttribute("type", "text/javascript");
            script.setAttribute("id", "grazit_script");
            document.getElementById("gt_widget_0").parentNode.appendChild(script);
        }
    }
})();

或者,您可以callbackF在范围上定义您的函数,window以便可以从闭包外部访问它:

(function () {
    window.callbackF = function(data) {
        eval(data.script);
    };

    window.onload = function () {
        if (url.indexOf('.html') > 0) {
            var gt_widget_id = document.createElement('div');
            gt_widget_id.setAttribute('id', 'gt_widget_0');
            var comments = document.getElementById('comments');
            comments.parentNode.insertBefore(gt_widget_id, comments);
            var comments = document.getElementById('comments');
            var script = document.createElement('script');
            script.setAttribute('src', "http://dev.example.com/wp/wpregister.asp?callback=callbackF&ver=2.5&url=" + encoded_url);
            script.setAttribute("type", "text/javascript");
            script.setAttribute("id", "grazit_script");
            document.getElementById("gt_widget_0").parentNode.appendChild(script);
        }
    }
})();
于 2013-02-17T15:22:55.970 回答