DataTables 重写Search框及 定义内部的事件

$.extend($.fn.dataTable.defaults, {
    
    
    //下面是默认的表样式结构
    dom: "<'row'<'col-sm-6'l><'col-sm-6'f>>" +
		"<'row'<'col-sm-12'tr>>" +
		"<'row'<'col-sm-5'i><'col-sm-7'p>>",
    //DT初始化完毕回调函数

    initComplete: function(settings) {
    
    
        var _$this = this;
        var searchHTML = '<label><input type="search" class="u-input" placeholder="请输入搜索内容" aria-controls="datatable1"></label>';
        //快捷操作的HTML DOM
		
		$(_$this.selector + '_wrapper .dataTables_filter').empty();
        $(_$this.selector + '_wrapper .dataTables_filter').append(searchHTML);

        //重写搜索事件
        $(_$this.selector + '_wrapper .dataTables_filter input').bind('keyup',
        function(e) {
    
    
            if (e.keyCode == 13 || (e.keyCode == 8 && (this.value.length == 0))) {
    
    
                _$this.api().search(this.value).draw();
            }
        });
        //全选,仅针对当前页
		$(_$this.selector + '_wrapper table.m-table th').first().on('click', 'input', function(e) {
    
    
			e.stopPropagation();
			var isChkAll = $(this).prop('checked');

			if(isChkAll) {
    
    
				$(this).attr('data-ischecked', true);
			} else {
    
    
				$(this).attr('data-ischecked', false);
			}

			$.each($(_$this.selector + '_wrapper table.m-table tbody tr td input'), function() {
    
    
				$(this).prop('checked', isChkAll);
				$(this).attr('data-ischecked', isChkAll);
			});
		})

		$(_$this.selector + '_wrapper table.m-table tbody tr td').on('click', 'input', function(e) {
    
    
			e.stopPropagation();
			console.log(111)
			var isChecked = $(this).prop('checked');
			var isCfm = true;
			var chk;
			var headInput = $(_$this.selector + '_wrapper table.m-table th input');

			if(isChecked) {
    
    
				$(this).attr('data-ischecked', true);
				$.each($(this).parents('tr').siblings(), function() {
    
    
					chk = $(this).contents().find('input').attr('data-ischecked');
					if(chk !== 'true') {
    
    
						isCfm = false;
					}

				});

				headInput.prop('checked', isCfm);
				headInput.attr('data-ischecked', isCfm);

			} else {
    
    
				$(this).attr('data-ischecked', false);
				headInput.prop('checked', isChecked);
				headInput.attr('data-ischecked', isChecked);
			}
		})

		$(_$this.selector + '_wrapper').on('page.dt', function(e) {
    
    
			e.stopPropagation();
			setTimeout(function() {
    
    
				var headInput = $("table.m-table th input");
				var isChecked = headInput.attr('data-ischecked', false);
				headInput.prop('checked', false)
				$.each($("table.m-table tbody tr input"), function() {
    
    
					$(this).prop('checked', false);
					$(this).attr('data-ischecked', false);
				});

			}, 50)
		})
    }
});


//初始化DT
var t = $('#example').DataTable({
    
    
    //......

    //自己需要的其他属性

});

参考资料

多条件查询和多列搜索
事件回调
dom 表单控制元素的操作

猜你喜欢

转载自blog.csdn.net/u013270347/article/details/87363827