为了账号安全,请及时绑定邮箱和手机立即绑定

如何使用 PHP 或 JavaScript 在网页正文中显示描述元标记的内容?

如何使用 PHP 或 JavaScript 在网页正文中显示描述元标记的内容?

PHP
翻翻过去那场雪 2024-01-19 20:59:07
我的网站以 class.page.php 构造函数/析构函数开始,其中包含元信息、页面标题和页脚。<?phpclass page{    private $title;    private $pageDescription;        public function __construct($title, $pageDescription){    $this->title = $title;    $this->pagedescription = $pageDescription;<!DOCTYPE html><html><head><title>Page Title</title><meta name="description" content="My Page Description;">//  … etc …    function __destruct()    {//  … etc …    }}?>每个页面都以这个 PHP 脚本开始,要求 class.page.php 并将该页面的标题和描述插入到头部。<?phprequire_once("inc/class.page.php");// Insert title, page description.$page = new page('My Page Title','My Page Description');?>我的目标是能够从元标记插入描述内容......<meta name="description" content="I want this also to show up between the h2 tags.">h2...在正文中的标签之间,即:<h2>How do I insert the page description here?</h2>我能够让页面标题显示在标签之间h1,如下所示,但我无法弄清楚如何对元描述内容执行类似的操作。<h1 id="pagetitle"></h1><script>    document.getElementById('pagetitle').innerHTML = document.title;</script>我更愿意为此找到一个 PHP 解决方案(以及页面标题)。但我也很乐意使用 JavaScript 来完成此操作。
查看完整描述

1 回答

?
芜湖不芜

TA贡献1796条经验 获得超7个赞

您可以使用选择器选择一个<meta name="description">元素meta[name=description]:


const content = document.querySelector('meta[name=description]').getAttribute('content');

document.getElementById('pagetitle').textContent = content;

<meta name="description" content="I want this also to show up between the h2 tags.">

<h1 id="pagetitle"></h1>

另请记住,仅在有意插入 HTML 标记时才使用innerHTML- 如果您只想插入文本,请textContent改为使用。(innerHTML不太合适,速度较慢,并且如果设置的内容不可信,则可能允许执行任意代码)



查看完整回答
反对 回复 2024-01-19
  • 1 回答
  • 0 关注
  • 34 浏览

添加回答

举报

0/150
提交
取消
意见反馈 帮助中心 APP下载
官方微信