jQuery变量包含“和”

时间:2012-05-22 10:06:12

标签: javascript jquery

是否可以用'替换postbody变量中的'而不实际编辑postbody变量内容

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/

4 个答案:

答案 0 :(得分:3)

创建一个元素并设置其文本,然后您不必对其进行编码:

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

答案 1 :(得分: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>";

答案 2 :(得分:0)

如果你真的想要替换字符串中的内容,只需使用replace():

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

答案 3 :(得分: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/