简体   繁体   English

如何评估jQuery追加中的javascript变量?

[英]How to evaluate javascript variable inside jQuery append?

I have an array of objects ( array ), each with a property containing a URL string that routes to an image. 我有一个对象arrayarray ),每个对象都有一个属性,该属性包含路由到图像的URL字符串。 I am trying to use jQuery to loop through this array and append each object's image into a div . 我正在尝试使用jQuery遍历此数组并将每个对象的图像附加到div Here is my code: 这是我的代码:

for (var i = 0; i < array.length; i++) {
    $('#div').append("<img src=\"array[i].URL\" alt=\"pic\">");
}

Note: I used the backslashes to escape the quotes in the img tag. 注意:我使用反斜杠来转义img标签中的引号。

The javascript is not evaluating inside the append method and it is simply printing "array[i].URL" for the image address on the page. javascript不在append方法内部求值,而只是在页面上打印“ array [i] .URL”作为图像地址。

Can someone give me a heads-up on what I'm doing wrong here? 有人可以告诉我我在这里做错了什么吗?

You have a bunch of options: 您有很多选择:

  1. $() and attr : $()attr

     for (var i = 0; i < array.length; i++) { $('#div').append( $('<img alt="pic">').attr("src", array[i].URL) ); } 
  2. String concatenation: 字符串串联:

     for (var i = 0; i < array.length; i++) { $('#div').append( '<img src="' + array[i].URL + '" alt="pic">' ); } 
  3. In ES2015+, you have template strings : 在ES2015 +中,您具有模板字符串

     for (var i = 0; i < array.length; i++) { $('#div').append( `<img src="${array[i].URL}" alt="pic">` ); } 

    Note the ${ and the } — the bit in-between them is evaluated by the JavaScript engine and swapped in a that point. 请注意, ${} –它们之间的位由JavaScript引擎评估,并在那一点交换。 Also note that they're quoted with backticks, not single or double quotes. 另请注意,它们用反引号引起来,而不是单引号或双引号。

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

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