javascript中使用this传递当前对象本身详解
传入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>


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

被折叠的 条评论
为什么被折叠?



