将变量分配给 url 失败 (JavaScript DOM)
Assign variable to url failed (JavaScript DOM)
为什么URL不接受这样的变量值
让 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>
因为当在 引号内时,它只是字母 "p"、"i" 和 "c"。但是当它 在引号外 时,它是一个用于查找值的标识符。
document.body.style.backgroundImage = "url(pic)";
// ^^^^^^^^^^−−−−−− string, the letters inside
// have no special meaning to
// JavaScript
对比
// vvv−−−−−−−−−−− identifier
document.body.style.backgroundImage = "url('" + pic + "')";
// ^^^^^^^ ^^^^−−−− strings
为什么URL不接受这样的变量值 让 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>
因为当在 引号内时,它只是字母 "p"、"i" 和 "c"。但是当它 在引号外 时,它是一个用于查找值的标识符。
document.body.style.backgroundImage = "url(pic)";
// ^^^^^^^^^^−−−−−− string, the letters inside
// have no special meaning to
// JavaScript
对比
// vvv−−−−−−−−−−− identifier
document.body.style.backgroundImage = "url('" + pic + "')";
// ^^^^^^^ ^^^^−−−− strings