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);});

 

posted @ 2018-08-30 10:00  光何  阅读(2340)  评论(0编辑  收藏  举报