我已经使用 Angular JS 和老式 JavaScript 创建了一个简单的代码编辑器,现在我想添加一个代码预览工具。
这是我用来动态创建 iframe、将其添加到 DOM 并填充使其工作所需的元素的代码:
...
function updatePreview() {
var iFrame, doc, styleElm, jQueryElem, styles, javascript;
var container, $head, $body;
var $jsRequirements = [], addditionalJS = [], $cssRequirements = [];
//set base requirements for iframe element
$jsRequirements = [
'http://ajax.googleapis.com/ajax/libs/jquery/1.7.2/jquery.min.js',
'http://ajax.googleapis.com/ajax/libs/jqueryui/1.8.23/jquery-ui.min.js',
];
$additionalJS = [
'js/libs/main.js',
'js/libs/plugin.slideshow.js'
];
$cssRequirements = [
'c/theme/jquery-ui-1.8.23.custom.css'
];
//set up a new HTML5 iFrame with basic styling
iFrame = document.createElement('iframe');
iFrame.className = "previewPane";
iFrame.style.height = "100%";
iFrame.style.width = "100%";
//append iFrame to previewContainer
container = document.getElementById('previewPanel');
container.appendChild(iFrame);
//init main iFrame content for manipulation
doc = iFrame.contentDocument || iFrame.contentWindow.document;
// init the inline style container element
styleElm = doc.createElement('style');
styleElm.setAttribute('rel','stylesheet');
styleElm.setAttribute('type','text/css');
styleElm.setAttribute('media', 'screen');
//grab css from CSS code pane
styles = cssCode.getValue();
//grab JS from the JS code pane
javascript = jsCode.getValue();
//write main HTML code
doc.open();
doc.write(htmlCode.getValue());
doc.close();
//must add any JS & styling *after* initial html code dump
$head = doc.getElementsByTagName('head')[0];
$body = doc.getElementsByTagName('body')[0];
//init script element and populate
//with local jQuery variable declaration
//for iFrame script execution
jQueryElem = doc.createElement('script');
jQueryElem.setAttribute('type','text/javascript');
//append the JS from the jsPanel to the same element
jQueryElem.appendChild(document.createTextNode(javascript));
//now the javascript
setupJSReqs($jsRequirements, doc, $head);
setupJSReqs($additionalJS, doc, $body);
styleElm.appendChild(document.createTextNode(styles));
$head.appendChild(styleElm);
$body.appendChild(jQueryElem);
}
setTimeout(updatePreview, 300);
});
}
function setupJSReqs(JSArray, container, target) {
for (var x in JSArray) {
var jsElem = container.createElement('script');
jsElem.setAttribute('type','text/javascript');
jsElem.setAttribute('src', JSArray[x]);
target.appendChild(jsElem);
}
}
这段代码在视觉上工作正常(即 chrome 开发工具在正确的位置显示所有元素)但我得到一个错误:
**Uncaught ReferenceError: $ is not defined**
我可能是错的,但我猜 dom 没有正确拉入 iframe jQuery 库。我可以通过 var $ = parent.$ 之类的方法来解决这个问题,但这不是理想的解决方案。
有什么建议可以解决这个错误??
谢谢