zoukankan      html  css  js  c++  java
  • jquery 里 $(this)的用法

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

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

  • 相关阅读:
    1-4 Autolayout
    1-3 UIScrollView
    lua 的语法糖
    javascript文档
    cocos2d 图片模糊
    a*寻路分析
    class按传递时分析
    mac 不再接受预览版提示
    OS X 10.11 El Capitan 三指拖动的开启方法
    mac系统卸载mono
  • 原文地址:https://www.cnblogs.com/kekjiuyue/p/6017229.html
Copyright © 2011-2022 走看看