<!DOCTYPE html>
<html>
<body>
<p>单击按钮来创建一些 BR 元素。</p>
<button onclick="myFunction()">试一试</button>
<p>当您单击该按钮时,会在 div 中的每个 span 元素之前插入一个 br 元素,从而在下面的文本中进行适当的换行。</p>
<div id="myDIV">
<span>Hello,</span>
<span>My name is Bob.</span>
<span>I live in Bobville.</span>
<span>I am 45 years old.</span>
</div>
<script>
function myFunction() {
var div = document.getElementById("myDIV");
var spans = div.getElementsByTagName("SPAN");
var i;
for (i = 1; i < spans.length; i++) {
var newElem = document.createElement("BR");
div.insertBefore(newElem, spans[i]);
}
}
</script>
</body>
</html>