JavaScript <br/>不起作用

时间:2018-04-28 22:17:29

标签: javascript break line-breaks

我正在尝试在javascript文件中插入换行符以自动添加到html标记中。我在谷歌搜索,但无法获得有关如何正确执行此操作的任何信息。

截图: screenshot

(function() {
	
	//Array of cars
	var car = ['Dodge', 'Nissan', 'Honda', 'Ford', 'Ferrari', 'Lamborghini', 'Audi', 'Porsche', 'Maserati', 'Bentley'];
	//Length of array
	var arrayLength = car.length;
	//Message
	var msg = '';

	//Loop through the items in the array
	for (var i = 0; i < arrayLength; i++) {
		//Current car to the message
		msg += "The car is: " + car[i] + "<br />";
	}

	//Upading HTML
	var el = document.getElementById("car");
	el.textContent = msg;
	
}());
<!DOCTYPE html>
<html lang="en">
<head>
	<meta charset="utf-8">
	<link rel="stylesheet" type="text/css" href="../../../css/style.css">
</head>
<body>
	<div class="wrapper">
	<header>
		<h1>Page 5</h1>
	</header>
	<h2 id="car">Getting stuff from javascript with id="car"</h2>
	<footer>
	</footer>
	<script src="05.js"></script>
	</div>
</body>
</html>

1 个答案:

答案 0 :(得分:2)

你需要使用innerHTML才能插入<br/> wish是一个html标签

(function() {
	
	//Array of cars
	var car = ['Dodge', 'Nissan', 'Honda', 'Ford', 'Ferrari', 'Lamborghini', 'Audi', 'Porsche', 'Maserati', 'Bentley'];
	//Length of array
	var arrayLength = car.length;
	//Message
	var msg = '';

	//Loop through the items in the array
	for (var i = 0; i < arrayLength; i++) {
		//Current car to the message
		msg += "The car is: " + car[i] + "<br />";
	}

	//Upading HTML
	var el = document.getElementById("car");
	el.innerHTML = msg;
	
}());
<!DOCTYPE html>
<html lang="en">
<head>
	<meta charset="utf-8">
	<link rel="stylesheet" type="text/css" href="../../../css/style.css">
</head>
<body>
	<div class="wrapper">
	<header>
		<h1>Page 5</h1>
	</header>
	<h2 id="car">Getting stuff from javascript with id="car"</h2>
	<footer>
	</footer>
	<script src="05.js"></script>
	</div>
</body>
</html>