Uncaught TypeError: Cannot read property 'className' of undefined(主图显示不出来)
在clear_main[i].className = clear_main[i].className
.replace('main-i_active', ' ');
这一行提示除了错误,然后整个主图是空白的。
自己检查了好几遍仍不知道是哪里出了问题,还请有经验的大神能帮我看一下,十分感谢!
<body> <div class="slider"> <!--0.修改 view->Template(关键字替换),增加template id--> <div class="main"> <div class="main-i" id="template_main"> <div class="caption" id="main_{{index}}"> <h2>{{h2}}</h2> <h3>{[h3}}</h3> </div> <img src="images/{{index}}.jpg"/> </div> </div> <div class="ctrl" id="template_ctrl"> <a class="ctrl-i" id="ctrl_{{index}}" href="javascript:switchSlider({{index}});"><img src="images/{{index}}.jpg"/></a> </div> <script type="text/javascript"> //1.数据定义(实际环境中应由后台给出) var data = [ {img:1,h1:'Creative',h2:'DUET'}, {img:2,h1:'Friendly',h2:'DEVIL'}, {img:3,h1:'Tranquilent',h2:'COMPATRIOT'}, {img:4,h1:'Insecure',h2:'HUSSLER'}, {img:5,h1:'Loving',h2:'REBEL'}, {img:6,h1:'Passionate',h2:'REBEL'}, {img:7,h1:'Crazy',h2:'FRIEND'} ]; //2.通用函数 var g = function(id) { if (id.substr(0, 1) == '.') { return document.getElementsByClassName(id.substr(1)); } return document.getElementById(id); }; //3.添加幻灯片 function addSliders() { //3.1获取模版 var tpl_main = g('template_main').innerHTML .replace(/^\s*/, '') .replace(/\s*$/, ''); var tpl_ctrl = g('template_ctrl').innerHTML .replace(/^\s*/, '') .replace(/\s*$/, ''); //3.2定义最终输出html的变量 var out_main = []; var out_ctrl = []; //3.3遍历所有数据,构建最终输出的html for( var i=0; i<data.length;i++ ) { var _html_main = tpl_main .replace(/{{index}}/g,data[i].img) .replace(/{{h2}}/g,data[i].h1) .replace(/{{h3}}/g,data[i].h2); var _html_ctrl = tpl_ctrl .replace(/{{index}}/g,data[i].img); out_main.push(_html_main); out_ctrl.push(_html_ctrl); } //3.4把html回写到对应的dom里 g('template_main').innerHTML = out_main.join(' '); g('template_ctrl').innerHTML = out_ctrl.join(' '); } //5.幻灯片切换 function switchSlider(n){ //5.1获得要展现的幻灯片和控制按钮dom var main = g('main_'+n); var ctrl = g('ctrl_'+n); //5.2获得所有幻灯片以及控制按钮 var clear_main = g('.main-i'); var clear_ctrl = g('.ctrl-i'); //5.3清楚他们的active样式 for(var i=0; i<clear_ctrl.length;i++) { clear_main[i].className = clear_main[i].className .replace('main-i_active', ' '); clear_ctrl[i].className = clear_ctrl[i].className .replace('ctrl-i_active', ' '); } //5.4为当前控制按钮和幻灯片附加样式 main.className += 'main-i_active'; ctrl.className += 'ctrl-i_active'; } //4.何时处理幻灯片输出 window.onload = function () { addSliders(); switchSlider(1); } </script> </div>