Welcome toVigges Developer Community-Open, Learning,Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
3.1k views
in Technique[技术] by (71.8m points)

js的一个创建Select的一个问题

可以帮我看下吗,刚学,实在想不明白,为什么在创建option之前获取到它,body加了一个div就没有获取到select里面的option
`<!DOCTYPE html>
<html lang="en">
<head>

<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Document</title>

</head>
<body>
</body>
<script>

const body = document.body;
body.appendChild(document.createElement('select'));
console.log(body.children[1]);
body.children[1].appendChild(document.createElement('option')).innerHTML=77;

</script>
</html>

image


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

你写的script再body的外面,但是html是不允许这样的写法的。编译的时候script会被插到body里面。
因此,你加了一个div并且插入了一个select,此时的文档结构是

<div></div>
<script></script>
<select></select>

这个时候你用children[1]获取的实际上是script标签,所以option是被插到script里面去了。

你下面的写法是ok的,因为你插入的select的序列号就是1,注意,序列号是从0开始的。


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to Vigges Developer Community for programmer and developer-Open, Learning and Share
...