gpt4 book ai didi

动态添加内容时Javascript引用问题

转载 作者:行者123 更新时间:2023-12-02 20:24:27 26 4
gpt4 key购买 nike

我正在尝试动态添加存储在变量中的内容。但是,单引号会引起问题。

var dynamicelementcode = $("<div id='container'>" + data +  "</div>");
dynamicelementcode.prependTo($('#wholecontainer')).hide().fadeIn(300).slideDown(1000);

如果数据变量包含单引号,则会破坏我的代码。我怎么解决这个问题? data 变量从服务器端 php 脚本获取其内容。

任何 php/js/jquery 解决方案都值得赞赏

编辑:

PHP 代码服务器端

$comment_body = "The boy's bicycle";

echo '{ "author": "'.$author.'", "message": "'.$comment_body.'","parentid": "'.$parent_id.'","currentid": "'.mysql_insert_id().'","timestored": "'.$timestampa.'" }';

Jquery 代码,客户端

var newrootcomment = $("<div class='comment'><div class='comment-holder'><div class='comment-body'>"+ data.message + "</div> <abbr class='timestamp' title=''>" + data.timestored + "</abbr><div class='aut'>" + data.author + "</div> <a href='#comment_form' class='reply' id='id"+ data.currentid + "'>Reply</a> </div> </div>");
newrootcomment.prependTo($('#wholecontainer')).hide().fadeIn(300).slideDown(1000);

最佳答案

var dynamicelementcode = $('<div id="container">').text(data)

jQuery text function自动为您转义引号。

<小时/>

UPD。仅转义单引号:

var dynamicelementcode = $('<div id="container">').html(data.replace(/'/g,'&#039;'))
<小时/>

UPD 2. 如果您查看页面的源代码,您会看到类似 "message": 'The boy's bike' 的内容 - 这是一个语法错误。

这是将 PHP 数据传递到 JavaScript 的更好方法,也可以使用引号:

$comment_body = "The boy's bicycle";
echo json_encode(array(
'author' => $author,
'message' => $comment_body,
'parentid' => $parent_id,
'currentid' => mysql_insert_id(),
'timestamp' => $timestamp
));

关于动态添加内容时Javascript引用问题,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/5068629/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com