监听事件动态改变

html代码:

<table class="table table-striped">
<thead>
<tr>

<th>分类ID</th>
<th>父ID</th>
<th>分类名称</th>
<th>分类状态</th>
<th>分类操作</th>
</tr>
</thead>
<tbody>
{foreach name="listcat" item="c"}
<tr>
<td>{$c.cat_id}</td>
<td>{$c.fid}</td>
<td>{$c.cat_name}</td>
<td>
{if condition="$c.is_show eq 1"}
<button class="btn btn-primary openclose">显示</button>
{elseif condition="$c.is_show eq 0" /}
<button class="btn btn-restore openclose">隐藏</button>
{/if}
</td>
<td>
<a href="{:url('Index/Category/delcat',array('cat_id'=>$c['cat_id']))}"><span class="fa fa-check text-navy">删除</span></a>
<a href="{:url('Index/Category/upcat',array('cat_id'=>$c['cat_id']))}"><span class="fa fa-check text-navy">编辑</span></a>
</td>
</tr>
{/foreach}
</tbody>
</table>

JS代码:

<script type="text/javascript">
    //不能监听动态的 只能监听静态的 监听document或者body或者td等
    $("td").on('click','.openclose',function () {
       var cat_id = $(this).parents('tr').find('td').eq(0).text();
       // console.log(cat_id);
       var show = $(this).text();
       var is_show = '';
       if (show=='显示'){
           is_show ='1';
       } else if(show=='隐藏'){
           is_show = '0';
       }
       // console.log(is_show);
       var td = $(this).parents('tr').find('td');
       $.ajax({
           type:"POST",
           async:false,
           data:{"cat_id":cat_id,"is_show":is_show},
           url:"{:url('Index/Category/changeStatus')}",
           error:function () {
               console.log('error');
           },
           success:function (data) {
               console.log(data);
               if (data=='0'){
                   td.eq(3).html("<button class=\"btn btn-restore openclose\">隐藏</button>\n");
               } else if (data=='1'){
                   td.eq(3).html("<button class=\"btn btn-primary openclose\">显示</button>\n");
               }
           }
       })
    })
</script>

猜你喜欢

转载自www.cnblogs.com/SofuBlue/p/9716878.html