场景:点击table某一td变色,并触发相应逻辑
代码:
1、加载table需要同步加载,并在加载完后绑定点击事件,或者异步加载在方法内部绑
$.ajax({ url: '/xxx', type:'post', dataType:'json', async: false }).then(function (result) { if (result.status==200){ //加载表格 } }); $('#table tr td').click(function() { //点击事件 })
或者异步加载,在方法内部绑定
$.ajax({ url: '/xxx', type:'post', dataType:'json' }).then(function (result) { if (result.status==200){ //加载表格 $('#table tr td').click(function() { //点击事件 }) } });
2、变色效果添加
先将原表格所有td样式置为默认
$('#table tr').each(function(i){ $(this).children('td').each(function(j){ $(this).css('backgroundColor','#ffffff'); $(this).css('color','#666'); }); });
然后将点击的td变色
$(this).css('backgroundColor','#3885E9'); $(this).css('color','#f9f9f9');
整合为
$('#table tr td').click(function() { //先改变td样式 $('#table tr').each(function(i){ $(this).children('td').each(function(j){ $(this).css('backgroundColor','#ffffff'); $(this).css('color','#666'); }); });
//然后改变td样式 $(this).css('backgroundColor','#3885E9'); $(this).css('color','#f9f9f9');
//业务逻辑 });
3 补充说明,前台绑定自定义标签后台获取
<td data-key="1" data-type="1">1</td>
var key = $(this).attr("data-key");