onclick() 函数不能与调用它的元素同名吗?

Can an onclick() function not have the same name as the element calling it?

本文关键字:元素 调用 函数 不能 onclick      更新时间:2023-09-26

所以我有这个按钮元素,无论我做什么,它都会拒绝触发它的onclick()函数,它让我发疯了一段时间:

<button type="button" id="newTreatment" name="newTreatment" onclick="newTreatment()" >Add a treatment</button>

我最终只是简单地更改了函数的名称,它立即起作用:

<button type="button" id="newTreatment" name="newTreatment" onclick="addTreatment()" >Add a treatment</button>

从那以后,我在其他几个按钮上对其进行了测试,并且一直遇到类似的问题。

那么这真的是正在发生的事情吗?onclick() 函数不能与 id 同名,如果它的元素?为什么?我尝试在网上寻找这个,但我找不到任何关于它的信息。

内联事件处理程序很神奇(即不直观)。

封闭<form>元素的属性位于内联事件处理程序的范围内。由于每个表单控件元素的名称都成为表单元素的属性,因此在事件处理程序中使用此类名称将改为引用该元素。

内联事件处理程序的作用域链大致为:

Global scope / properties of window
^
|
Properties of document (e.g. body)
^
|
Properties of enclosing form (e.g. newTreatment or submit)
^
|
Properties of <button id="newTreatment" /> (e.g. type, onclick)
^
|
Function scope of inline event handler
更近范围(例如表单)中的

绑定 较高范围(例如全局范围)中的影子绑定。

一个简单的解决方案是通过 window.newTreatment 显式引用全局变量。

我在这里更详细地描述了这一点。

这似乎在HTML5规范中被正式化。

假设您将元素包装在form中,这是因为命名元素作为属性添加到form中。

当您尝试调用 newTreatement 时,该范围内已经存在一个属性newTreatment。它认为你指的是该物业,并给了你一个错误

新治疗不是一个函数

请参阅为什么 JS 函数名称与元素 ID 冲突?和带有 id 的 DOM 树元素会成为全局变量吗?