将变量分配给网址失败(JavaScript DOM)

问题描述 投票:0回答:1

为什么URL不接受这样的变量值 let pic ='img_tree.png'; document.body.style.backgroundImage =“ url(pic)”;

但是接受“ pic”这样的变量值。 document.body.style.backgroundImage =“ url('” + pic +“')”;

<!DOCTYPE html>
<html>
<body>

<h1>Hello World!</h1>
<button type="button" onclick="myFunction()">Set background image</button>

<script>
function myFunction() {
	let pic = 'img_tree.png';
   // document.body.style.backgroundImage = "url(pic)"; ERROR
  document.body.style.backgroundImage = "url('"+pic+"')"; // working fine
}
</script>

</body>
</html>
javascript html dom background-image
1个回答
0
投票

因为引号是[[inside,所以只是字母“ p”,“ i”和“ c”。但是当它是outside引号时,它是一个用于查找值的标识符。

© www.soinside.com 2019 - 2024. All rights reserved.