doudiewen9435 2014-08-23 11:10
浏览 45
已采纳

将the_content()存储到javascript / jquery变量中

How can I do that ? Store the_content() into a variable . What I've tried :

<script type="text/javascript">
    window.the_content = "<?php the_content(); ?>";
</script>

and this

<?php 
    ob_start();
    the_content();
    $content = ob_get_clean();
?>

<script type="text/javascript">
    window.the_content = "<?php echo $content; ?>";
</script>

The problem is that what's echo-ed it's a multi-line string and that can't be stored as a javascript variable. I tried to trim() chop() htmlentities_decode() the string but it's useless.

I know that there's a function <?php echo get_the_content(); ?>that take off the html tags but the spaces and line-breaks are still there. I want to be able to parse the_content() via jquery .

Copy paste of the output from Google Chrome Developer Tool :

                                window.the_content = "<h1>Welcome to dasqwe tsqwe dwemo site</h1>
<p>&nbsp;</p>
<p>asdioquwidqwd</p>
<p>qwdoqwkdpqkwdkoqpwodkqwodpqwd</p>
<p>qwdkpoqwkdpqwokdpqwokdpqwkdpqwodkq</p>
<p>wdqwodkqpowkdpqwkdpqwkdopqwkdoq</p>
<p>wdqkowpdkqwpokdpoqkwdpqowkdpoqwkdqwd</p>
<p><span id="more-13"></span></p>
<h1>Page 2</h1>
<p>qwiodjiqwjdqiowjdioqwjdiqwd</p>
<p>qwdjoqwijdoqiwjdioqwjiodjqwodjqowdijas</p>
<p>dqoijwdioqjwdoqjwiodjqwodjqwdjasdqwodijqowdjqiowjdoqjdoad</p>
<p>qwodiqwjdoiqwdijoqwdqwiqiodijoqwdjiqwq</p>
<p>&nbsp;</p>
";
  • 写回答

3条回答 默认 最新

  • duanlv1366 2014-08-23 11:25
    关注

    Try using json_encode, it should escape most of the characters that would make it break

    <?php
        ob_start();
        the_content();
        $data = ob_get_contents();        
        ob_end_clean();        
    ?>
    window.the_content = <?php echo json_encode($data); ?>;
    

    You could also just strip out the new lines

    window.the_content = "<?php str_replace("
    ","",the_content()); ?>";
    

    Note that you would have to do other stuff to make sure it doesnt break, for instance escape double quotes etc.

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(2条)

报告相同问题?

悬赏问题

  • ¥15 写论文,需要数据支撑
  • ¥15 identifier of an instance of 类 was altered from xx to xx错误
  • ¥100 反编译微信小游戏求指导
  • ¥15 docker模式webrtc-streamer 无法播放公网rtsp
  • ¥15 学不会递归,理解不了汉诺塔参数变化
  • ¥15 基于图神经网络的COVID-19药物筛选研究
  • ¥30 软件自定义无线电该怎样使用
  • ¥15 R语言mediation包做中介分析,直接效应和间接效应都很小,为什么?
  • ¥15 Jenkins+k8s部署slave节点offline
  • ¥15 如何实现从tello无人机上获取实时传输的视频流,然后将获取的视频通过yolov5进行检测