我在jQuery循环中填充HTML标签。这意味着我的HTML代码位于字符串内。一切都可以,但是我不知道如何在我的HTML代码内检索JavaScript参数。
我尝试使用(BackSlash)或`(Backtick)逃脱,但仍然失败。
read_html += "https://example.org" + val.poster_path;
read_html += "<img src='https://example.org' + val.poster_path '>";
第一行对我来说还可以。但是我需要第二行代码来获得值。我已经阅读了一些有关此问题的文章,但我仍然没有得到答案。
我想要的就是将poster_path放在IMG标签中。
您需要像这样的串联字符串和变量:
read_html += '<img src="https://example.org/' + val.poster_path + '">';
摘要:
var val = {
poster_path: "something.html"
}
var read_html = '<img src="https://example.org' + val.poster_path + '">';
console.log(read_html)
,或者如果您更喜欢ES6模板文字(更简洁):
read_html += `<img src="https://example.org/${val.poster_path}">`;
请注意,以上代码将无法使用:
- 任何版本的Internet Explorer
- 边缘12或以下
- Firefox 33或以下
- 铬40或以下
- Safari 9或以下
- 歌剧28或以下
- Stackoverflow的堆栈片段(截至2018年12月)
caniuse链接
您可以使用`。
这样做使用** ** you need to use
$ {}`访问任何变量
let val ={
path : 'hello.img'
}
var read_html = `<img src='https://example.org' + ${val.path} '>`;
console.log(read_html)