2012-05-22 150 views
0

是它在所有可能的'更換'在postbody變量,而無需實際編輯postbody變量內容jQuery的變量包含「和」

var postbody = '<div class="postbody">this is tom's and bill's post</div>'; 
var postid = $('#post-content'); 
postid.append(postbody);​ 

http://jsfiddle.net/3nVrZ/

+1

你的代碼甚至不是有效的js ... –

+0

首先轉義'''或者你的JavaScript字符串中斷:'\''。 – Geert

+0

正確的appostophe是'不'(單引號) – Elen

回答

3

創建一個元素,並將其文本,那麼你就不必對其進行編碼:

var post = $('<div/>', { 'class': 'postbody' }); 
post.text("this is tom's and bill's post"); 
$('#post-content').append(post);​ 
+1

爲什麼downvote?如果你不解釋你認爲是錯誤的,它不能改善污染。 – Guffa

+0

+1 - 它比轉義引用更可讀:p.s.你錯過了一個''' – fcalderan

+0

因爲我在問是否有可能用postbody變量的字符串替換單引號而不需要改變它的內容 –

2

你可以使用

var postbody = '<div class="postbody">this is tom\'s and bill\'s post</div>'; 

var postbody = "<div class=\"postbody\">this is tom's and bill's post</div>"; 
+0

對不起,我Forogot提及,是否有可能做到這一點,而無需編輯postbody字符串 –

+0

你從哪裏得到'後'從PHP或書面? – thecodeparadox

+0

博客由內容由

0

如果你真的想在一個字符串替換的東西,只是使用替代():

var postbody = "<div class=\"postbody\">this is tom's and bill's post</div>"; 
postbody = postbody.replace(/\'/g, "&#39;"); 
0

嘗試使用此

var postbody = "<div class='postbody'>this is tom's and bill's post</div>"; 
var postid = $('#post-content'); 
postid.append(postbody);​ 

http://jsfiddle.net/ipsjolly/3nVrZ/1/