jQuery动态填充table 和select内容

版权声明:整理不易,转载请注明出处。 https://blog.csdn.net/linmengmeng_1314/article/details/84678265

jQuery 添加动态新内容有以下四个方法:

  1. append() - 在被选元素的结尾插入内容
  2. prepend() - 在被选元素的开头插入内容
  3. after() - 在被选元素之后插入内容
  4. before() - 在被选元素之前插入内容

表格操作

清空表的数据: 格式:$("#表格ID 要清空的部分").empty("");

其中要清空的部分,也可以是:thead tbody tr td

$("#tableOwner thead").empty(""); 
$("#tableOwner tbody").empty("");

也可以保留表头,清除表格内容,如下:其中J_tab_fam是table的id

$("#J_tab_fam  tr:not(:first)").html("");

或者是

$("#J_tab_fam  tr:not(:first)").empty(""); 

使用的比较多的也就是append了,这个不但可以在表格中动态添加数据,还可以用于下拉框中回显数据。

  1. HTML内容:初始化一个表格
<table id="tableOwner" >
	<thead>						
	</thead>
	<tbody>							
	</tbody> 
</table>
  1. 填充(html语句中要注意单双引号交替使用,外面使用双引号时,内部属性要用单引号,反之亦然)
/* 填充之前需要先清空,否则将会直接将新内容追加到表格的后面了 */
$("#tableOwner thead").empty(""); 
$("#tableOwner tbody").empty("");

$("#tableOwner thead").append('<tr><th>用户账号</th><th id="owner_th">管理员</th><th>操作</th></tr>');
$("#tableOwner tbody").append("<tr><td>" + user.userPhone + "</td>"
							+ "<td class='owner_td mouseOver' onclick='updateOwner(" + user.userId +")'>" + user.owner +"</td>"
							+ "<td><button type='button' onclick='update(" + user.userId +")' class='btn btn-primary tab-modify'>修改密码</button>"
							+ "&nbsp<button type='button' onclick='detail(" + user.userId +")' class='btn btn-primary tab-modify'>详情</button></td></tr>");

下拉框动态填充

  1. 首先在html中初始化一个下拉框
<select id="selectOwner" class="form-control-select" style="width:100%;height:34px;margin-top:20px;border: 1px solid #ccc;border-radius:4px"></select>
  1. js部分
    以ajax返回的内容为例:
success : function(data) {
	var len = data.data.length;
	var content = "";
	for(var i=0;i<len;i++){
		content += '<option>'+ data.data[i] +'</option>';
	}
	$(".form-control-select").append(content);
}

猜你喜欢

转载自blog.csdn.net/linmengmeng_1314/article/details/84678265