这个问题在这里已经有了答案:
disappearing google map
(2 个回答)
3个月前关闭。
上下文:我正在尝试学习一些 JavaScript 和 HTML。我有一些数组并想对它们进行标准化,以便它们的条目总和为 1。为此,我定义了一个名为 normalize 的函数(该函数将数组作为其参数)。一切正常,直到我尝试在我的主 .html 文件中作为按钮单击的一部分合并对我的 normalize 函数的调用。下面是一个工作虚拟示例,省略了数组内容。
<script>
function normalize () {return 1;};
</script>
<input type="button" onclick="console.log(normalize()); //prints undefined when clicked">
<script>
console.log(normalize()); // prints 1 as intended
</script>
但是,如果我将函数的名称更改为 normalize 以外的名称,则两个调用都可以正常工作:<script>
function foo () {return 1;};
</script>
<input type="button" onclick="console.log(foo()); //prints 1 when clicked">
<script>
console.log(foo()); // prints 1
</script>
我的问题是:当函数命名为 normalize 时,为什么 onclick 调用的行为不同?鉴于 onclick 似乎在我的一个数组上调用了一些外部规范化函数,我原以为它会抛出错误或其他什么东西。我快速搜索了其他 normalize 函数,我确实看到有一个 HTML DOM normalize 方法,但我不明白为什么调用它(如果它被调用!)而不是我想要的函数。 onclick normalize 调用是怎么回事?在此先感谢您提供的任何帮助!
最佳答案
这是不使用 onxyz
的众多原因之一-attribute-style 事件处理程序:它们在具有 的多重嵌套代码中执行手数范围内对象的方法。在这种情况下,您不小心运行了 Node.prototype.normalize
,你可以看到存在:
console.log("normalize" in Node.prototype);
我们甚至可以看到这是您的按钮正在使用的那个:
<input type="button" onclick="console.log(normalize === Node.prototype.normalize)">
Node.prototype.normalize
方法(引用上面的 MDN 链接)......puts the specified node and all of its sub-tree into a "normalized" form. In a normalized sub-tree, no text nodes in the sub-tree are empty and there are no adjacent text nodes.
使用
addEventListener
相反,所以 function normalize () {return 1;};
document.getElementById("the-button").addEventListener("click", () => {
console.log(normlize()); // Prints 1
});
<input type="button" id="the-button" value="Click Me">
我使用了
getElementById
的 ID在那个例子中,但你 不要必须使用 ID 才能工作。您只需要能够使用任何 CSS 选择器和 querySelector
来识别元素。或 querySelectorAll
.
关于javascript - onclick 正在调用哪个规范化函数?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/67826215/