2011-09-14 29 views
1

我裏面的文字股利:jQuery的多行文字問題

<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.=""> 

我在做什麼錯在這裏?

回答

3

的問題是,你缺少圍繞在標籤值的報價,但你不能只需添加引號,因爲如果描述文本中有引號,它仍然會中斷。

相反,試試這個。

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

這是否工作?我認爲第二個jQuery函數的參數是context元素 – jimbojw

+0

是的,它被添加到1.4中,你可以在這裏看到它:http://api.jquery.com/jQuery/#jQuery2 as「jQuery(html,props)」 – loganfsmyth

+0

+ 1.發揮先生 - 我不知道。:) – jimbojw

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

忘記了 「關於desc

+2

這將失敗,如果 '遞減' 有報價在它。 – loganfsmyth

1

你缺少引號的兩側。所有屬性值應在報價

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

和網址

src="'+url+'" 

f ROM W3C 屬性值應該始終用引號括起來 http://www.w3schools.com/html/html_attributes.asp

現場演示http://jsfiddle.net/pzC7b/8/

+0

如果'desc'中有引號,則會失敗。 – loganfsmyth

+0

一秒鐘,我會嘗試在jsfiddle – Samich

+0

它適用於jsfiddle。檢查你是否有像'url'等所有變量。我已將實時演示添加到答案 – Samich

2

其他的答案是正確的,因爲你錯過了引號,但是當描述包含報價,它打破了HTML你就會有下一個問題將是。我的建議是追加圖像,然後設置數據desc。

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

這將字符實體替換報價

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

結果+編碼網址:

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

例如在jsfiddle