连接变量,在我的情况下背景样式损坏

concatenate variable with background style broken in my case

本文关键字:背景 样式 损坏 情况下 我的 变量 连接      更新时间:2023-09-26
$("#home").append('<div style="background:url("http://example.com/images/'+obj[i]+'.jpg")"');

这是怎么回事?我想我已经正确关闭了它..

引号不匹配时遇到问题 - 需要转义url属性值中的双引号,或删除它们。您也没有正确关闭div标签。试试这个:

$("#home").append('<div style="background:url(http://example.com/images/' + obj[i] + '.jpg)"></div>');

示例小提琴

正在构建的字符串引起的问题:

'<div style="background:url("http://example.com/images/'+obj[i]+'.jpg")"'

让我们假设 obj[i]==1。

您的div 将如下所示:

<div style="background:url("http://example.com/images/1.jpg")"

请注意两个重要的问题:

  1. div 没有结束(">"字符(
  2. style 属性是 "background:url(" - 具有相同类型的引号会阻止导航器理解您。

尝试使用:

 $("#home").append('<div style="background:url(/'http://example.com/images/'+obj[i]+'.jpg/')">');

祝你好运!