我正在使用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> 发布于 2014-02-27 07:52:54
我不知道安全漏洞(虽然它确实使人们可以轻松地从控制台调用您的函数),但是全局命名空间非常拥挤,在其中定义函数或其他变量是有问题的,因为冲突的可能性很大。
为了避免这种情况,您可以使用DOM2 2风格的事件处理程序连接,并将所有内容包装在一个作用域函数中。例如:
<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支持的半现代浏览器,就可以使用任何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、闭包或其他几种之一 )的原因之一。
https://stackoverflow.com/questions/22062181
复制相似问题