gpt4 book ai didi

javascript - 为什么要避免在网页中直接定义 JavaScript 函数?

转载 作者:行者123 更新时间:2023-11-30 12:47:23 25 4
gpt4 key购买 nike

我正在使用 Cast 软件(代码质量分析工具),它说

避免在网页中直接定义 JavaScript 函数

我有一些违反该规则的示例。我很好奇为什么 Cast 将其确定为安全漏洞或必须遵守的规则?

示例:

<!DOCTYPE html>
<html>
<body>

<h1>My First JavaScript</h1>
<p>Click the button to display the date.</p>
<p id="demo"></p>

<button type="button" onclick="myFunction()">Try it</button>

<script>
function myFunction()
{
document.getElementById("demo").innerHTML = Date();
}
</script>

</body>
</html>

最佳答案

我不知道安全漏洞(虽然它确实让人们很容易从控制台自己调用你的函数),但是全局命名空间非常拥挤,并且定义函数或其中的其他变量是有问题的,因为存在很多潜在的冲突。

为避免这种情况,您使用 DOM2 样式的事件处理程序连接并将所有内容包装在一个作用域函数中。例如:

<button type="button" id="myButton">Try it</button>

(function() {
document.getElementById("myButton").addEventListener("click", myFunction);

function myFunction() {
}
})();

请注意,仍然有流行的(虽然正在减弱)使用的浏览器没有 addEventListener(主要是 IE8,但我认为这将是一个缓慢的死亡)。但是它有 attachEvent

您的按钮不必有 ID,只要您能以某种方式找到元素实例即可。即使 IE8 也有 querySelector/querySelectorAll,所以如果你只需要用 QSA support 支持半现代浏览器,您可以使用任何 CSS 选择器:

// Get the first 'button' on the page
btn = document.querySelector("button");

// Get the first 'button' with class 'foo' on the page
btn = document.querySelector("button.foo");

// Get all 'button's with class 'foo' on the page
list = document.querySelectorAll("button.foo");

这个事件是人们使用像 jQuery 这样的浏览器实用程序库的原因之一。 , Closure , 或 any of several others .

关于javascript - 为什么要避免在网页中直接定义 JavaScript 函数?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/22062181/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com