main.js:26 Uncaught TypeError: Cannot read property 'prepend' of undefined at alertSuccess (main.js:26) at HTMLDocument.<anonymous> (main.js:11) at j (jquery.js:3073) at Object.fireWith [as resolveWith] (jquery.js:3185) at Function.ready (jquery.js:3391) at HTMLDocument.I (jquery.js:3407)
"use strict"; var pageSize = 10 //全局pageSize , messageBoxNum = 0 , alertBox ; //共用函数 $(document).ready(function() { alertSuccess(screen.availWidth+" "+screen.availHeight) alertBox = $(".alert-box"); alertBox.css("left",$("html").width()/2-alertBox.width()/2); }); function alertClose(name){ function close(){ alertBox.children("div[name='"+name+"']").remove(); } setTimeout(close,3000); } function alertSuccess(str){ var name="messageBox"+messageBoxNum; messageBoxNum++; alertBox.prepend(` <div class="alert alert-success" name="`+name+`"> <a href="#" class="close" data-dismiss="alert"> × </a> `+str+` </div> `); alertClose(name); }
上面因为调用alertBox在
alertBox = $(".alert-box");
之前,所以alertBox还没定义,是undefined,因而alertBox没有prepend函数
但初学时很容易看到这个报错就混乱,这里只需要将alertBox = $(".alert-box");放到最前面即可