您的位置:首页 > Web前端 > JavaScript

javascript Uncaught TypeError: Cannot read property ... of undefined

2017-08-24 13:37 691 查看
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");放到最前面即可
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: 
相关文章推荐