1、将Select的选项添加到结果中
$add.on('click', function () { $.ajax({ url: '/Includes/Controls/AssociatedCountrysHandler.ashx', data: { action_type: 'add-associated-country', useraddress_id: userAddressID, country_id: $select.val() }, success: function (data) { var html=''; $.each(data, function (i, val) { html += '<li>' + val.CountryName + "<a class='models-delete delete-associate-country' data-id='" + val.CountryID + "' href='#'><img src='/content/images/icon/cross.png' alt='Delete' /></a>" + '</li>'; }) $('.associated-country-list').html(html); } }); return false; });
2、点击‘X’,移除对应内容。
$('.associated-country-td').on('click', '.delete-associate-country', function () { var $this = $(this); if ($this.hasClass('disabled')) { return false; } if (confirm('Are you sure you wish to remove this item?')) { $this.addClass('disabled').prop('disabled', true); $.ajax({ url: '/Includes/Controls/AssociatedCountrysHandler.ashx', data: { action_type: 'delete-associated-country', useraddress_id: userAddressID, country_id: $this.data('id') }, success: function (data) { $this.closest("li").fadeOut(function () { $this.remove(); }); } }); } return false; });
注意:
1、当后台返回的数据为一个数组时,对数组进行遍历的方法:
后台返回数据:
对数组进行遍历:
$.each(data, function (i, val) { html += '<li>' + val.CountryName + "<a class='models-delete delete-associate-country' data-id='" + val.CountryID + "' href='#'><img src='/content/images/icon/cross.png' alt='Delete' /></a>" + '</li>'; })
2、注意移除目标时,事件绑定在父类元素上,因为添加目标时对应的部分被刷新,原有的按钮已失效,所以需要绑定在未被刷新的父类元素上,确定删除目标存在于刷新之后的页面中。