abstrait:想要實現(xiàn)從本地中加載json文件,通過事件來動態(tài)的插入到ul中時,遇到了一小bughtml中代碼是這樣的<ul class="easyui-tree" id="tt"></ul>js中的代碼$(".next-menu:nth-child(1) a").click(function()&
想要實現(xiàn)從本地中加載json文件,通過事件來動態(tài)的插入到ul中時,遇到了一小bug
html中代碼是這樣的
<ul class="easyui-tree" id="tt"></ul>
js中的代碼
$(".next-menu:nth-child(1) a").click(function() { var $IDstr = $(this).attr("id"), $treeIDNum = parseInt($(this).attr("treeID")), jsonURL = "json/" + $IDstr + ".json", node; addAttr2Tree(jsonURL); changeImgSrc($treeIDNum); }); }); function changeImgSrc(nodeID){ var node = $("#tt").tree('find', nodeID); if(node){ $("#tt").tree('SELECT', node.target); } if (node.attributes) { $("#img-box").attr("src", node.attributes.url); } } function addAttr2Tree(URL){ $("#tt").tree({ url: URL, method: "get", animate: true, lines: true }); }
起初是想通過一個按鈕的點擊事件來動態(tài)的加載tree的內(nèi)容就是如上代碼,addAttr2Tree 是用來將點擊按鈕時對應(yīng)的本地json數(shù)據(jù)加到html中的ul標(biāo)簽中, changeImgSrc 是對tree節(jié)點的一些選中操作以及圖片的加載,但是無論怎么調(diào)試,總是會出現(xiàn)一條錯誤
無法獲取attributes屬性?。?!我反復(fù)確認attributes是完整無缺的放在json文件里的而且總是第一次點擊按鈕時才會出現(xiàn)這種錯誤,第二次及其以后,這種錯誤是沒有的
后來我就想到,是不是因為json數(shù)據(jù)動態(tài)加載的速度比不上程序代碼執(zhí)行的速度?!
果然不出我所料!easyui中tree自帶了一個方法onLoadSuccess 當(dāng)數(shù)據(jù)成功加載時,才會執(zhí)行一些操作
所以
$(".next-menu:nth-child(1) a").click(function() { var $IDstr = $(this).attr("id"), $treeIDNum = parseInt($(this).attr("treeID")), jsonURL = "json/" + $IDstr + ".json", node; addAttr2Tree(jsonURL); $("#tt").tree({ onLoadSuccess: function(){ changeImgSrc($treeIDNum); } }); });
代碼改成這樣就可以了。
更多關(guān)于 jQuery Easyui異步加載tree的問題解析請關(guān)注PHP中文網(wǎng)(ipnx.cn)其他文章!