混合字符串和变量在jQuery中

时间:2014-08-25 23:14:06

标签: jquery html

我在使用此代码时遇到了问题

  output.html('<img  width="200" src="uploads/'+response.responseText+'" height="300" >');

输出:

   <img width="200" height="300" 1269050260.png""="" src="uploads/">

应该是:

   <img width="200" height="300"  src="uploads/1269050260.png">

我尝试了很多方法,例如:

 output.html('<img  width="200" src="uploads/'+response.responseText+'" height="300" >');
 output.html('<img  width="200" src="uploads/"'+response.responseText+'" height="300" >');
   .....

但是当我尝试这个时:

  output.html("<img width='200' src='uploads/"+response.responseText+" height='300' >");

它给出了

  <img width="200" 300'="" src="uploads/"1074374482.png" height=">

这也错了。

修改

当我尝试以下建议时:

   output.html("<img width='200' src='uploads/"+response.responseText+"' height='300' >");

我得到了这也是错误的。

  <img width="200" height="300" src="uploads/"977165688.png"">

当我尝试:

    output.html("<img width='200' src='uploads/977165688.png' height='300' >"); // this works

2 个答案:

答案 0 :(得分:3)

最好逃避&#34;而不是尝试使用这样的引用规则。试试这个:

output.html("<img  style=\" width: 200px; height: 300px; \" src=\"uploads/" + response.responseText + "\">");

Fiddle

如果这不起作用,那么你还有其他问题。

修改

同样,<img>标记不推荐使用width和height属性。不要使用它们。请改用CSS。示例已更新

答案 1 :(得分:1)

jQuery html()接受HTMLString作为参数,如果你不确定response.responseText,你应该尝试将其解析为HTML(并且你应该编码它,因为它将属于src属性):

output.html($.parseHTML('<img  width="200" src="uploads/' + encodeURIComponent(response.responseText) + '" height="300" >'));