简体   繁体   English

javascript | 单引号之间的字符串文本问题

[英]javascript | string text between single quotes problem

the 'bg' is recognised as a variable.. its supposed to be text.. i also tried the double quotes but the url() only accepts single quotes url 'bg' 被识别为变量.. 它应该是文本.. 我也尝试了双引号,但 url() 只接受单引号 url

 var ahref = '<a href="#" style="background-image: url('bg');"></a>'; var newhref = ahref.replace('bg', newThumbnailUrl)

JavaScript string interpolation works differently. JavaScript 字符串插值的工作方式不同。

You can use Template literals , using the backtick ` ` .您可以使用模板文字,使用反引号` `

 var bg = 'your-image.jpg'; var ahref = `<a href="#" style="background-image: url('${bg}');"></a>`; console.log(ahref);

Or you can concatenate strings with the addition operator + .或者,您可以使用加法运算符+连接字符串。

 var bg = 'your-image.jpg'; var ahref = '<a href="#" style="background-image: url(\'' + bg + '\');"></a>'; console.log(ahref);

The url() property does not require quotes, only in certain conditions. url()属性不需要引号,仅在某些条件下。

A url, which is a relative or absolute address, or pointer, to the web resource to be included, or a data uri, optionally in single or double quotes. url,它是指向要包含的 web 资源的相对或绝对地址或指针,或者是数据 uri,可选择单引号或双引号。 Quotes are required if the URL includes parentheses, whitespace, or quotes, unless these characters are escaped, or if the address includes control characters above 0x7e.如果 URL 包含括号、空格或引号,则需要引号,除非这些字符被转义,或者地址包含高于 0x7e 的控制字符。 source资源

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

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