JS動態事件綁定問題


今天搞一個連環套的動態選項展示,需要給下拉框動態綁定事件,誰知綁定中出現問題,總是執行第一次綁定的時間而后續綁定的事件沒有被觸發。

 1 //重寫增加行方法
 2 function initMainItem(gridId){  3     jqgrid = $('#' + gridId);  4     var colModel = jqgrid.jqGrid().getGridParam("colModel");  5     var rowid ="rowid" + new Date().getTime();  6     jqgrid.jqGrid("addRowData", rowid, JSON.stringify(colModel), "last");  7     jqgrid.editRow(rowid, true);  8     var optTd = $("#" + rowid + " td[aria-describedby='basMgmtGridIdGrid_opt']");  9     var buttonStr= '<a href="#" class="btn btn-xs btn-danger" onclick="delRowData(\'' +
10             rowid+'\')"><i class="fa fa-trash"></i>&nbsp;刪除</a>&nbsp;&nbsp;'; 11  optTd.html(buttonStr); 12     jqgrid.jqGrid('setSelection',rowid); 13     var option = ""; 14     for(var key in itemData) { 15         option += "<option role='option' value='" + key + "'>" + mainItemDict[key] + "</option>"; 16  } 17     var mainItem = $("#" + rowid + " select[name=mainItem]"); 18  mainItem.html(option); 19     mainItem.change(function () {initSubItem(mainItem);}); 20  initSubItem(mainItem); 21 } 22 
23 function initSubItem(mainItem) { 24     var mainItemKey = mainItem.val(); 25     var priceItems = itemData[mainItemKey]; 26     var option = ""; 27     for(var key in priceItems) { 28         option += "<option role='option' value='" + key + "'>" + key + "</option>"; 29  } 30     var subItem = mainItem.parent("td").next("td").children(); 31  subItem.html(option); 32     subItem.change(function () {initItem(subItem, priceItems);}); 33  initItem(subItem, priceItems); 34 } 35 
36 function initItem(subItem, priceItems) { 37     var subItemKey = subItem.val(); 38     var priceItem = priceItems[subItemKey]; 39     var unitItem = subItem.parent("td").next("td"); 40     unitItem.html("<span class='form-control' style='background-color:transparent;border-color:transparent'>" + unitDict[priceItem.unit] + "<span>"); 41 }

  注意兩個動態綁定,其實很簡答的知識,綁定新事件前要清除舊事件,因為js默認不覆蓋,這些都是學過的,就是不出錯get不到啊。

  改為:

1 subItem.unbind("change").change(function () {initItem(subItem, priceItems);});

 


免責聲明!

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



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