當遇到循環table時,查看其中的td、tr屬性和值會有一點的麻煩。此時就必須使用$(this)來解決這一類的問題了。
1.直接使用
2.間接使用
<table>
<?php foreach($shoplist as $v){ ?>
<tr>
<td>{$v.goods_name}</td>
<td>顏色:灰色</td>
<td id="num">
<div class="c_num" goods_id="{$v.goods_id}">
<input type="text" value="{$v.number}" name="" class="car_ipt" />
</div>
</td>
<td id="jiage">¥{$v['number'] * $v['price']}</td>
<td id="update"><a goods_id="{$v.goods_id}">刪除</a></td>
</tr>
<?php }; ?>
</table>
<script>
//1.直接在事件中使用 (父級事件發生后,獲取子類的值)
$("#update a").click(function(){
$goods_id=$(this).attr("goods_id");
})
//2.$(this).parent().next().html()不起作用是,可分為兩步去完成
//這是$(this)的第二種用法(間接使用,可與find()、parent()等,聯合使用)
$(".c_num").click(function(){
div=$(this).parent(); //第一步
$goods_id=$(this).attr("goods_id");
$number=$(this).find(".car_ipt").val();
//alert($number+$goods_id);
$.ajax({
type:"get",
url:"{:U('home/buycar/number')}",
data:"goods="+$goods_id+"&number="+$number,
success:function(msg){
div.next("td").html("¥"+msg); //第二步
}
})
})
</script>
html
代碼如下 | 復制代碼 |
<p class="item"> <input type="text" name="meta_key[164]" value="file1" size="20" /><a href="/18" id="164" class="button remove">remove</a> </p> |
需求說明:
鼠標點擊‘remove’鏈接,根據ajax的返回值刪除頁面元素。
無效的方法
代碼如下 | 復制代碼 |
$('.remove').bind('click',function(){ $.ajax({ type:'post', url:$(this).attr('href'), dataType : 'json', data:{id : $(this).attr('id')}, success:function(msg){ if(msg.error==0){ alert(msg.msg); }else{ $(this).parent().remove(); //此處無法獲得父級元素 } } }); return false; }); |
有效的方法
代碼如下 | 復制代碼 |
$('.remove').bind('click',function(){ div=$(this).parent(); //先獲取父級元素 $.ajax({ type:'post', url:$(this).attr('href'), dataType : 'json', data:{id : $(this).attr('id')}, success:function(msg){ if(msg.error==0){ alert(msg.msg); }else{ div.remove(); //再刪除 } } }); return false; }); |
其他類似問題也可以通過相同方法解決