码迷,mamicode.com
首页 > Web开发 > 详细

jquery 里 $(this)的用法

时间:2016-10-31 22:11:05      阅读:246      评论:0      收藏:0      [点我收藏+]

标签:jquery   query   tab   无法   无效   color   put   else   err   

  当遇到循环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;
   });

其他类似问题也可以通过相同方法解决

 

jquery 里 $(this)的用法

标签:jquery   query   tab   无法   无效   color   put   else   err   

原文地址:http://www.cnblogs.com/kekjiuyue/p/6017229.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!