javascript中使用this传递当前对象本身详解

本文详细讲解了JavaScript中如何使用`this`关键字来传递当前对象本身,包括通过`this`修改对象的`src`属性、获取`class`属性,以及在`onclick`事件中转换为对象获取属性的方法。

传入this修改src属性的值

<!DOCTYPE html>
<html>
<head>
    <meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
    <title>用this传递当前对象本身</title>
    <meta charset="utf-8" />
</head>
<body>
<img src="https://img0.baidu.com/it/u=1777758054,3959029696&fm=15&fmt=auto&gp=0.jpg" onclick="changeImg(this)" alt=""/>
<img src="https://img2.baidu.com/it/u=2729595542,2246014510&fm=26&fmt=auto&gp=0.jpg" onclick="changeImg(this)" alt=""/>
 
<script>
    var myImages = [
        "https://img0.baidu.com/it/u=1978160468,524406277&fm=26&fmt=auto&gp=0.jpg",
        "https://img0.baidu.com/it/u=275268402,807334776&fm=26&fmt=auto&gp=0.jpg",
        "https://img0.baidu.com/it/u=456327488,2048329174&fm=26&fmt=auto&gp=0.jpg",
        "https://img0.baidu.com/it/u=3105626230,3521945106&fm=26&fmt=auto&gp=0.jpg"
    ];
 
    function changeImg(that) {
        var newImgNumber = Math.round(Math.random() * 3);
 
        //确保随机生成的图片索引不和当前的一样
        while (that.src.indexOf(myImages[newImgNumber]) != -1) {
            newImgNumber = Math.round(Math.random() * 3);
        }
 
        that.src = myImages[newImgNumber];
    }
</script>
</body>
</html>

默认显示
在这里插入图片描述
点击图片显示

在这里插入图片描述

获取this的class属性


<span class="liu_autoer_float_right" onclick="demo(this)" > </span>

<script type="text/javascript">
//这里是留言点赞功能
      function demo(a){
         console.log($(a).attr("class"));
      }
//这里是留言回复点赞功能
</script>

onclick(this) 转对象获取属性

<!DOCTYPE html>
<html>
<head>
    <meta http-equiv="Content-Type" content="text/html; charset=utf-8"/>
    <title>用this传递当前对象本身</title>
    <meta charset="utf-8"/>
</head>
<body>
<a href="javascript:void(0);" onclick="get_this(this)" userId="qipa250">奇葩天地网</a>

<script src="https://csdnimg.cn/public/common/libs/jquery/jquery-1.9.1.min.js" type="text/javascript"></script>

<script>
    function get_this(that) {
        var thisObj = $(that);//js对象转jquery对象
        var userId = thisObj.attr("userId");
        alert(userId);
    }
</script>
</body>
</html>

在这里插入图片描述

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值