简体   繁体   English

为什么我的JavaScript语句不能正确更改背景图像?

[英]Why doesn't my JavaScript statement change the background image properly?

I am trying to set a background Image of a div with this code .But it is not working. 我正在尝试使用此代码设置div的背景图像。但是它不起作用。 If i use backgroundColor instead then it works fine . 如果我改为使用backgroundColor,那么它可以正常工作。 Can anyone tell me whats wrong with this . 谁能告诉我这怎么了。 Sorry for noob question. 对不起,菜鸟问题。

<button onclick="document.getElementById('ab').style.backgroundImage='url("pexel.jpg")'">Click me</button>

Syntax error, see below 语法错误,请参见下文

<button onclick="document.getElementById('ab').style.backgroundImage='url(pexel.jpg)'">Click me</button>

Use 'url(pexel.jpg)' instead of 'url("pexel.jpg")' 使用'url(pexel.jpg)'代替'url("pexel.jpg")'

The quotes in the url() assignment are what's causing the issue. url()分配中的引号引起了问题。 You need to escape them correctly. 您需要正确地逃避它们。

<button onclick="document.getElementById('ab').style.backgroundImage='url(\'pexel.jpg\')';">Click me</button>

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM