原本标题是:element.onclick = fun与<element οnclick="fun()">的区别,但是提示含有非法字符。

问题背景:

在看this指向的时候看到了这个,有的时候通过给DOM元素绑定监听事件,来触发某些事件处理函数(如点击当前元素时修改该元素样式等),如果绑定的监听函数里面用到了this,上面两种方式可能会有不同的效果。

试验代码:

<!DOCTYPE html>
<html lang="en">
<head><meta charset="UTF-8"><title>区别onclick不同绑定方式</title>
</head>
<body>
<div id="div1" style="width: 80px;height: 80px" >DIV1,点击触发更改颜色</div>
<div id="div2" style="width: 80px;height: 80px" onclick="changeBackground2()">DIV2,点击触发更改颜色</div>
<script>//this指向当前元素,本质是调用对象里面的方法div1.onclick = changeBackground1;function changeBackground1(){console.log(this);this.style.color = '#cc0000';}//this指向window对象,本质是调用了嵌套函数,先调用onclick(),再调用changeBackground()//嵌套函数中的this要么指向window(非严格模式)要么undefined(严格模式)function changeBackground2() {console.log(this);this.style.color = '#cc0000';  //TypeError:color undefined}
</script>
</body>
</html>

试验结果:

可以很明显的看到,第一种方式达到了想要的效果,第二种方式直接报错了。通过控制台打印的内容和报的错能够分析出基本原因,this指向不同,第一个指向了div元素(div1),颜色修改成功,第二个指向了window对象,找不到color属性报错。为什么this的指向会不一样?

原因分析:

1.copying

element.onclick = doSomething;

这个实际上是把doSomthing这个函数复制一份给了element的onclick属性,因此触发点击事件时,this指向的是运行时调用它的对象element。原解释:The function is copied in its entirety to the onclick property (which now becomes a method). So if the event handler is executed this refers to the HTML element and its color is changed.

------------ window --------------------------------------
|                                                        |
|                                                        |
|                                                        |
|   ----------------                                     |
|   | HTML element | <-- this         -----------------  |
|   ----------------      |           | doSomething() |  |
|               |         |           -----------------  |
|          -----------------------          |            |
|          |copy of doSomething()|  <-- copy function    |
|          -----------------------                       |
|                                                        |
----------------------------------------------------------

2.referring

<element onclick="doSomething()">

这种方式只是让onclick属性指向了函数doSomething,并没有把doSomething函数的内部实现也包含进来,因此当触发点击事件时,只是找到onclick属性,然后告诉你去找doSomething吧,我这没具体实现,找到doSomething后,这时候里面的this已经指向window了,其实是在window下调用的doSomething函数。原解释:

you do not copy the function! Instead, you refer to it, and the difference is crucial. The onclick property does not contain the actual function, but merely a function call:

doSomething();

So it says “Go to doSomething() and execute it.” When we arrive at doSomething()the this keyword once again refers to the global window object and the function returns error messages.

------------ window --------------------------------------
|                                          / \           |
|                                           |            |
|                                          this          |
|   ----------------                        |            |
|   | HTML element | <-- this         -----------------  |
|   ----------------      |           | doSomething() |  |
|               |         |           -----------------  |
|          -----------------------         / \           |
|          | go to doSomething() |          |            |
|          | and execute it      | ---- reference to     |
|          -----------------------       function        |
|                                                        |
----------------------------------------------------------

3.两个的区别就是:第一种方式是完全复制;第二种只是指向了函数。

3.1

element.onclick = doSomething;
alert(element.onclick)
//结果如下function doSomething()
{this.style.color = '#cc0000';
}

doSomething是element对象的一个属性(方法),类似下面:

var element = {value: "123",onclick: function doSomething() {console.log(this.value);}}
element.onclick();//123

3.2

<element onclick="doSomething()">
alert(element.onclick)
//结果如下function onclick()
{doSomething()
}

doSomething是一个嵌套函数,类似下面:

var element = {value: "123",onclick: function onclick(){doSomething();}}
function doSomething() {console.log(this.value);
}
element.onclick();//undefined

嵌套函数中的this要么指向window(非严格模式),要么undefined(严格模式)

参考链接:https://www.quirksmode.org/js/this.html

https://blog.csdn.net/u013584334/article/details/81192899

element.onclick = fun与element onclick=fun()的区别相关推荐

  1. Selenium Xpath元素无法定位 NoSuchElementException: Message: no such element: Unable to locate element

    用的佳哥的python基于selenium的学习通健康自动填报 但是今天突然报错了. Error Message Message: no such element: Unable to locate ...

  2. IE8报错:Unable to modify the parent container element before the child element is closed

     转自:http://blog.csdn.net/xinwang/article/details/9786447 IE8中会报 HTML Parsing Error: Unable to modi ...

  3. android onclick fragment,Android Fragment onClick按钮方法

    我试图调用我的onClick(View v)XML中的方法,但不能使用Fragment.这是错误. 01-17 12:38:36.840: E/AndroidRuntime(4171): java.l ...

  4. python中bs4.element.tag_python – BeautifulSoup标签是类型bs4.element.NavigableString和bs4.element.Tag...

    我正在尝试在维基百科文章中搜索一个表,并且每个表元素的类型似乎都是< class'bs4.element.Tag'>和< class'bs4.element.NavigableStr ...

  5. element中的横线,element的tab,下划线不显示的问题

    页面重新加载,tabs选中tab的下划线不显示,如图所示: 和点击后的效果,如下,是不一样的 computed: { barStyle: { get: function get() { var _th ...

  6. React自定义组件使用onClick传参注意:onClick只是一个名字而已!

    核心: React自定义组件不是真实DOM,所以没有onClick属性, 如果对React自定义组件写上onClick,也只是个单纯的名字而已,onClick的值作为props传到子组件. 例如: f ...

  7. JavaScript中 onclick()、click()触发点击事件的区别

    function load(){ //下面两种方法效果是一样的document.getElementById("target").onclick();document.getEle ...

  8. element走马灯自动_vue Element UI走马灯组件重写

    1.element ui走马灯组件 -- carousel 分析一波源代码: carousel/src/main.vue 文件为 el-carousel文件主要功能 carousel/src/item ...

  9. element table 单选按钮_vue + Element el-table表格里面使用单选radio按钮

    今天再改bug的时候,孙子张口就来,便是一个需求,要在表格里面加单选radio按钮,将选中的数据内容传到另一页面展示. 顾名思义,只能单选某一条数据,于是就跑到element官网找路子,结果没有找到想 ...

最新文章

  1. 剑指offer六十一之序列化二叉树(待补充)
  2. java、上转型对象
  3. Genymotion出现unknown generic error和This may occur if you are using a proxy错误的解决方案
  4. 数字图像的加载、显示和输出
  5. CodeForces - 1348D Phoenix and Science(贪心)
  6. Arcgis Server初学笔记(一)
  7. Java基于注解和反射导入导出Excel
  8. https://gogs.io/
  9. 产品经理|竞品分析(附《竞品分析报告》模板)
  10. 离散傅里叶变换(DFT)
  11. STM32单片机GPIO口简介
  12. 面试之springboot是什么?
  13. java 图片添加蒙版处理
  14. flea-db使用之封装JDBC接入
  15. win10蓝牙鼠标、耳机无法连接,无蓝牙开关标志解决方案
  16. 中科院成都计算机应用研究所毕业,中国科学院成都计算机应用研究所考研问答...
  17. 超级删除PowerTools
  18. vue项目--资产管理系统
  19. 【经典教程】怎样能把SWF反编译为fla?
  20. c++多线程调用python脚本

热门文章

  1. 如何设计一门语言(十)——正则表达式与领域特定语言(DSL)
  2. 人工智能:第五章 计算智能(2)
  3. LeetCode18.四数之和 JavaScript
  4. spring的Autowired和@Resource的区别是什么
  5. 初探面向对象编程之oop与设计模式
  6. 《嵌入式系统开发之道——菜鸟成长日志与项目经理的私房菜》——第1章 系统•嵌入•硬件 01-01 Welcome on board!...
  7. 《Adobe Illustrator CC经典教程》—第0课0.1节简介
  8. php中的foreach和js中的foreach的用法和区别
  9. mini CentOS7 安装 mysql
  10. 海量存储之十八–一致性和高可用专题