分享web开发知识

注册/登录|最近发布|今日推荐

主页 IT知识网页技术软件开发前端开发代码编程运营维护技术分享教程案例
当前位置:首页 > 网页技术

js ?this

发布时间:2023-09-06 01:55责任编辑:郭大石关键词:js
<script type="text/javascript"> ????function to_green(){ ???????this.style.color="green"; ???} ???function init_page(){ ???var example=document.getElementById("example"); ???????example.onclick=to_green; ??} ??window.onload=init_page;</script><a href="#" id="example" style="color: red;">点击变绿</a>

定义:this是包含它的函数作为方法被调用时所属的对象,
 1、包含它的函数。2、作为方法被调用时。3、所属的对象。
function to_green(){
??this.style.color="green";
}
to_green();
函数所属的对象 ??默认情况是window 并没有style这个属性
通过赋值操作,example对象的onclick得到to_green的方法,那么包含this的函数就是to_green()喽,
onclick事件是让example对象调用了to_green()函数,所以this指向example



<!DOCTYPE html><html><body><p>点击下面的按钮,循环遍历对象 "person" 的属性。</p><button onclick="myFunction()">点击这里</button><p id="demo"></p><script>function myFunction(){var x;var txt="";var person={fname:"Bill",lname:"Gates",age:56}; for (x in person){txt=txt + person[x];}document.getElementById("demo").innerHTML=txt;}</script></body></html>

 for  in 循环

js ?this

原文地址:https://www.cnblogs.com/zuichumx0826/p/9063658.html

知识推荐

我的编程学习网——分享web前端后端开发技术知识。 垃圾信息处理邮箱 tousu563@163.com 网站地图
icp备案号 闽ICP备2023006418号-8 不良信息举报平台 互联网安全管理备案 Copyright 2023 www.wodecom.cn All Rights Reserved