(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是未定义的?那是为什么?
答案 0 :(得分: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);
}
}
})();