javascript - 插入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>
这些文章是用户生成的,结果输出因每次创建的内容而异。
解决方案
$fullArticle 中的行返回和制表符导致了问题。以下使用 html 说明符和反引号``而不是引号''的代码更改解决了该问题:
$("#more").html(`<?php echo $fullArticle; ?>`);
还可以删除 $fullArticle 中的换行符和制表符,并通过以下方式继续使用引号:
$fullArticle = preg_replace('/[\n\r\t]/', '', $fullArticle);
有关该问题的更清晰示例,您可以查看此帖子。
推荐阅读
- php - WordPress - wp-image-NUMBER 不会在某些 WordPress 网站上添加 alt、宽度和高度?
- python - 如何使用 subprocess.run() 在 Python 中运行 cmd 命令
- bash - Docker删除多个图像并保留最后两个
- c# - 从本地网络C#获取所有IP时出现问题
- mysql - 如何获取没有来自特定用户的任何评论的帖子
- javascript - 如何通过css检查列表是否包含第一个元素
- javascript - 验证错误:如果使用函数调用执行严格模式函数,则其“this”值将未定义
- sql - 多个 AND 条件 - ORACLE SQL
- python - google-auth OAuth 2.0 如何保存访问令牌以供进一步使用
- python - 获取 discord.ext.commands.errors.CommandInvokeError: