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


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">
        &times;
    </a>
    `+str+`
    </div>
    `);
    alertClose(name);
}

上面因為調用alertBox在 

  alertBox = $(".alert-box");
之前,所以alertBox還沒定義,是undefined,因而alertBox沒有prepend函數

但初學時很容易看到這個報錯就混亂,這里只需要將alertBox = $(".alert-box");放到最前面即可


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM