技术实践

给你涨一个小知识点,关于DOM元素

DOM(Document Object Model) 的繁荣可以追溯至 1990 年代后期微软与 Netscape 的“浏览器大战”,双方为

羊先生的头像
羊先生2020.12.26 · 2 分钟阅读 · 121 阅读
给你涨一个小知识点,关于DOM元素封面
文章正文还需 2 分钟

背景

我目前所在公司的有很多项目是前后端不分离项目,基本都是jq+dom操作

代码

html 复制代码
<!DOCTYPE html>
<html lang="en">
<head>
	<meta charset="UTF-8">
	<title>Document</title>
</head>
<body>
	<button onclick="download()">测试button</button>
	<a onclick="download()">测试a</a>
	
	<script type="text/javascript">
	
		function download() {
	      		console.log(1);
		}
	
	</script>
</body>
</html>

结果

点击button结果正常,点击a标签报错
image.png

原因

HTML 5 中为 增加了 download 属性,所以在 a 上调用 download() 会提示 download is not a function,因为所有的属性都是字符串。

同样,如果把表单里面的某个控件 id 设置为 submit,会导致表单提交 form.submit() 出错,错误信息和这个类似,submit is not a function。

证明

html 复制代码
<!DOCTYPE html>
<html lang="en">
<head>
	<meta charset="UTF-8">
	<title>Document</title>
</head>
<body>
	<button onclick="test()">测试button</button>
	<a onclick="test()">测试a</a>
	<script type="text/javascript">
	
		function test() {
	      console.log(1);
		}
	
	</script>
</body>
</html>

正常执行

image.png

什么是 DOM?

https://developer.mozilla.org/zh-CN/docs/Web/API/Document_Object_Model/Introduction