Jquery多行文本问题

时间:2011-09-14 06:05:29

标签: javascript jquery debugging html5

我有一个带文字的div:

<div>A description of dreamstill. It is a music site that is social and other stuff where you cando this and that and pretty much anything that your heart allows. This is probably as long as the description will get.</div>

然后我提取文本并将其作为data-url属性粘贴在图像上:

var desc = div.text();
div.replaceWith('<img class="center" src='+url+' data-desc=' + desc + ' />');

问题是图像正在生成如下:

<img class="center" src="http://featherfiles.aviary.com/2011-09-09/aae3b22a952841cd9c0d6a26a5867325.png" data-desc="A" description="" of="" dreamstill.="" it="" is="" a="" music="" site="" that="" social="" and="" other="" stuff="" where="" you="" cando="" this="" pretty="" much="" anything="" your="" heart="" allows.="" probably="" as="" long="" the="" will="" get.="">

我在这里做错了什么?

5 个答案:

答案 0 :(得分:3)

问题是您缺少标记中值的引号,但您不能只添加引号,因为如果描述文本中包含引号,它仍然会中断。

相反,试试这个。

var desc = div.text();
div.replaceWith(
  $('<img />', {
    "class": "center",
    "src": url,
    "data-desc": desc
  })
);

答案 1 :(得分:2)

其他答案是正确的,因为你缺少引号,但是当描述包含引号并且它破坏HTML时,你将遇到的下一个问题。我的建议是附加图像,然后设置data-desc。

div.replaceWith(
  $('<img class="center" src="' + url + '"/>').attr('data-desc', desc)
);

答案 2 :(得分:1)

div.replaceWith('<img class="center" src="'+url+'" data-desc="' + desc + '" />');

忘记了desc

两边的“

答案 3 :(得分:1)

你错过了引号。所有属性值都应在引号

div.replaceWith('<img class="center" src='+url+' data-desc="' + desc + '" />');

和url to

src="'+url+'"
来自w3c的

属性值应始终用引号括起来 http://www.w3schools.com/html/html_attributes.asp

现场演示http://jsfiddle.net/pzC7b/8/

答案 4 :(得分:1)

这将替换带有字符实体的引号

desc.replace(/\"/g, '&quot;')

结果+编码网址:

div.replaceWith('<img class="center" src="' + encodeURI(url) + '" data-desc="' + desc.replace(/\"/g, '&quot;') + '" />');

jsfiddle

上的示例
相关问题