我们可以将所有所有信息作为参数传递给内联事件处理程序吗?

时间:2019-01-01 01:14:52

标签: javascript html

我在互联网上找到了此代码,作者将元素的id作为第一个参数传递给事件处理程序。请参阅下面的示例。

直到今天,我的印象是我们只能将event信息作为事件处理程序的参数传递,而且我可以看到我们也可以将当前元素的id作为参数传递给事件处理程序

此内容在MDN上有何记载?有人可以指向我的文档吗?

<!DOCTYPE html>
<html>
    <head>
        <title></title>
    </head>
    <body>
        <input type="text" value="Hello" onchange="someFunction(id,event);" id="someId"/>
    </body>
    <script type="text/javascript">
        function someFunction(id,event){
            console.log(id); //Printing "someId"
            console.log(event.target.value); //It is printing updated value 
        }
    </script>
</html>

1 个答案:

答案 0 :(得分:2)

我相信您可以将元素原型链中某个位置的任何属性称为独立变量:

function someFunction(id, onclick, children, clientTop) {
  console.log(id);        // someId
  console.log(onclick);   // note, this is null, not undefined!
  console.log(children);  // length 0, but still an HTMLCollection
  console.log(clientTop); // 2
}
<input type="text" value="Hello" onchange="someFunction(id, onclick, children, clientTop);" id="someId" />

就像内联处理程序包装在with(this)中一样。引用元素对象或元素原型链中存在的属性名称,将导致该属性值被引用。

因此,像

这样的内联处理程序
<input onchange="somestr">

被解释为类似

// assume this refers to that input element:
with (this) {
  eval(somestr);
}

请注意,event位于不同的类别中-它不是元素的属性,而是全局window.event