jquery 裡 $(this)的用法

來源:互聯網
上載者:User

標籤: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)的用法

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.