2013-12-18 17 views
0

我與RSS訂閱工作。我想通過鏈接和標題給這樣的JavaScript函數。如何通過其中包含JavaScript函數的動態字符串(」「)

'<a href="javascript:void(0)" onclick="shareFb(\''+item.link+'\',\''+item.title+'\')"></a>' 

這item.link和item.title是動態生成的,如果鏈接包含一些單詞,如(Facebook)等。(')單引號和其他字符出現問題,並且瀏覽器控制檯發生錯誤uncaught syntaxerror: unexpected identifier.如果標題和鏈接我傳遞包含純文本然後我能夠通過這些作爲參數。是否有任何想法,使其工作。

+1

使用encodeURIComponent方法(); – Praveen

+1

爲什麼不只是$('a')。click(function(){shareFb(item.link,item.title);}); – Andrew

+0

''使用此功能 – AmGates

回答

1

試試這個:

'<a href="javascript:void(0)" onclick="shareFb(\''+encodeURIComponent(item.link)+'\',\''+encodeURIComponent(item.title)+'\')"></a>' 
0

在該項目冠軍,與\'

變化

item.title 

取代'的出現次數,以

item.title.replace('\'', '\\'') 
0

就像你說的,有問題的字符。在服務器端,嘗試轉義item.link和item.title。例如,在C#中,您將使用:HttpUtility.UrlEncode。在JavaScript中,您可以使用encodeURI()。然後當你想解碼參數時,使用decodeURI()。

相關問題