首页 > 解决方案 > 插入php变量时JQuery函数失败

问题描述

有一个非常简单的 JQuery 函数,当单击“...更多”这个词时,它会替换 HTML 跨度标记中的数据。其目的是在文章末尾添加更多文本:

<span id="more" style = "color: blue; cursor:pointer;">...more</span>
<script>
//To get remainder of article when clicked on "...more"
    $(document).ready(function(){
        $("#more").click(function(){ 
                   $("#more").text('<?php echo $fullArticle; ?>');
                   $("#more").css('color','black');
                   $("#more").css('cursor','');
        });
    });
</script> 

当我插入 php 变量时,这不起作用。当我点击时,没有任何变化。当我使用文本字符串$("#more").text('some data');代替 PHP 变量时,脚本工作正常,发生替换。我读过的文章似乎表明这是将 php 变量传递给 JQuery 函数的正确方法,但我一定遗漏了一些东西。

编辑:$fullArticle 的典型内容:

<div>
<h2>Why do we use it?</h2>
<p>It is a long  to using 'Content here, content here', 
    making it look like readable English.</p><p> Many desktop publishing packages and 
   web page editors now use Lorem Ipsum as their default model text, and a search 
   for 'lorem ipsum' will e years, sometimes by accident, 
   sometimes on purpose (injected humour and the like).<img style="float: 
   left; margin: 10px;" title="DSC00286.JPG" src="images/images91/imageID11424.jpg" 
   alt="" width="200" height="154" /></p>
</div>
<div>
<h2>Where does it come from?</h2>

这些文章是用户生成的,结果输出因每次创建的内容而异。

标签: javascriptphpjquery

解决方案


$fullArticle 中的行返回和制表符导致了问题。以下使用 html 说明符和反引号``而不是引号''的代码更改解决了该问题:

$("#more").html(`<?php echo $fullArticle; ?>`);

还可以删除 $fullArticle 中的换行符和制表符,并通过以下方式继续使用引号:

$fullArticle = preg_replace('/[\n\r\t]/', '', $fullArticle);

有关该问题的更清晰示例,您可以查看此帖子


推荐阅读