js動態生成的dom無法啟動事件(click,mouseover......)
阿新 • • 發佈:2019-01-10
解決辦法:
1.將執行事件的程式碼放在生成dom的 function 裡面 $.ajax({ url: "url", //json檔案位置 // url: "serialization.json", //json檔案位置 type: "post", //請求方式為get //data: "{pareId:0}", async: true, contentType: "application/json", dataType: "json", //返回資料格式為json success: function(data) { var serialization = data.d; gridster = $(".gridster ul").gridster({ widget_selector: "li", widget_base_dimensions: [200, 179], widget_margins: [2.6, 4], autogenerate_stylesheet: true, resize: { enabled: 'false', //允許放縮 handle: '.resize' //html標籤的css類名,按住此標籤可以對網格進行放縮 }, serialize_params: function($w, wgd) { //$w為要輸出位置的網格物件(li),wgd為該網格物件的座標物件,包括col,row,size //_x,size_y四個成員 return { id: $w.attr("id"), x: wgd.col, y: wgd.row, sn: $w.find(".sn").text(), name: '', //機器名字 location: '', duty: $w.find(".duty").text(), //負責人 vender: '', venderCncId: '', spec: '', productDT: '1900/1/1', buyDT: '1900/1/1', remark: '', user: '', percent: $w.find(".percent").text() } }, draggable: { handle: 'li img', //模組內定義拖動的元素<header>,這裡也支援jquery選擇器,如"span.drag_handle",標識拖動的是<header>. start: function(eent, ui) { //alert('開始拖') }, //開始拖觸發的,從點選開始! stop: function(eent, ui) { //結束拖動,從放下模組開始! var s = gridster.serialize(); //$(selector).serialize()輸出序列化表單的字串,檔案上傳控制元件(例如:<input type="file" name="myfile"/>)型別的表單資料會被自動忽略,也就是說不會出現在序列化字串中。 $.ajax({ type: "POST", url: "url", //請求地址 async: true, contentType: "application/json", dataType: "json", //返回資料格式為json data: "{strLocationJson:'" + JSON.stringify(s) + "'}", success: function(data, status) { console.log("success!") } //必須設定為同步模式,即回撥函式執行完畢後才向下執行(unload頁面) }); //也可以從start裡面開始拖的時候顯示個提交的框框, 拖完了點選提交後進行ajax請求資料庫! } }, //設定serialize()方法的返回值 }).data('gridster'); gridster.remove_all_widgets(); //重新整理 $.each(JSON.parse(serialization), function() { gridster.add_widget('<li id=' + this.id + '><img src=img/' + this.statusColor + '.png/><span class=sn>' + this.sn + '</span><span class=duty>' + this.user + '</span><span class=status style=color:' + this.statusColor + '>' + this.status + '</span><span class=program>' + this.program + '</span><span class=percent>' + this.percent + '%' + '</span><span class= edit></span><span class=delete></span></li>', this.width, this.height, this.x, this.y, "", "", this.id); }); // 滑鼠劃過事件 $("#gridster li ").mouseover( function() { //顯示刪除圖示 $(this).find(".edit").css("display", "block"); $(this).find(".delete").css("display", "block"); });$("#gridster li").mouseout( function() { //隱藏刪除圖示 $(this).find(".edit").css("display", "none"); $(this).find(".delete").css("display", "none"); }); } });
2.async:false//將模式設定成同步就可以了
$.ajax({
type : "post",
url : url,
dataType : "json",
async:false//設定成同步就可以了
}).done(function(data){
});