为什么此代码不起作用(以及如何修复)? [英] Why this code doesn't work (and how to repair it)?
本文介绍了为什么此代码不起作用(以及如何修复)?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
此问题是另一个我的问题.
代码是:
<script type='text/javascript'>
var scripts = [
"http://www.---.com/include/jquery-1.8.3.min.js",
"http://www.---.com/include/functions.js",
"http://www.---.com/include/myjs.js",
"http://www.---.com/include/plugins/bxslider/bxslider.js"
];
function downloadJSAtOnload() {
for( var i=0; i<scripts.length; i++ ) {
var element = document.createElement('script');
element.src = scripts[i];
document.body.appendChild(element);
}
$(document).ready(function(){
$('#mainslide .bxslider').bxSlider({
slideWidth: '960',
mode: 'vertical',
speed: '500',
captions: false,
pager: false,
controls: false,
nextText: 'Next',
prevText: 'Prev',
auto: true,
autoHover: true,
pause: 3000
});
});
}
if (window.addEventListener) window.addEventListener('load', downloadJSAtOnload, false);
else if (window.attachEvent) window.attachEvent('onload', downloadJSAtOnload);
else window.onload = downloadJSAtOnload;
</script>
生成的错误为未捕获的ReferenceError:未定义$".
The error generated is "Uncaught ReferenceError: $ is not defined ".
奇怪的是,在许多浏览器和版本中,一切都可以完美运行(幻灯片,灯箱等).仅在IE8和Safari 4中,警报就会显示给用户.
The strange is that everything works perfectly (slideshow, lightbox, ...) in lots of browsers and verions. Just in IE8 and Safari 4 an alert is showed to the user.
推荐答案
由于您正在向文档中动态添加JS库,因此在加载脚本后需要使用回调函数来初始化bxSlider.理想情况下,应在bxSlider加载后调用回调.
Since you are dynamically adding the JS libraries to the document, you will required a callback function after the scripts are loaded in order to initialize the bxSlider. Ideally the callback should be called after the bxSlider has loaded.
element.setAttribute("type","text/javascript");
element.onload = callBackFunction;
document.body.appendChild(element);
var callBackFunction() {
$('#mainslide .bxslider').bxSlider({
slideWidth: '960',
mode: 'vertical',
speed: '500',
captions: false,
pager: false,
controls: false,
nextText: 'Next',
prevText: 'Prev',
auto: true,
autoHover: true,
pause: 3000
});
}
这篇关于为什么此代码不起作用(以及如何修复)?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文