[英]How can I use either PHP or JavaScript to display the contents of the description meta tag in the body text of a web page?
My site starts with a class.page.php constructor/destructor that contains the meta info, page title and footer.我的网站以 class.page.php 构造函数/析构函数开头,其中包含元信息、页面标题和页脚。
<?php
class page{
private $title;
private $pageDescription;
public function __construct($title, $pageDescription){
$this->title = $title;
$this->pagedescription = $pageDescription;
<!DOCTYPE html>
<html lang="en">
<head>
<title>Page Title</title>
<meta name="description" content="My Page Description;">
// … etc …
function __destruct()
{
// … etc …
}
}
?>
Each page begins with this PHP script to require the class.page.php and insert that page's title and description into the head.每个页面都以这个 PHP 脚本开始,需要 class.page.php 并将该页面的标题和描述插入到头部。
<?php
require_once("inc/class.page.php");
// Insert title, page description.
$page = new page('My Page Title','My Page Description');
?>
My goal is to be able to insert the description content from the meta tag…我的目标是能够从元标记插入描述内容......
<meta name="description" content="I want this also to show up between the h2 tags.">
…in between the h2
tags in the body text, ie: ...在正文中的
h2
标签之间,即:
<h2>How do I insert the page description here?</h2>
I'm able to get the page title to show between the h1
tags as shown below, but I haven't been able to figure out how to do something similar with the meta description content.我能够让页面标题显示在
h1
标签之间,如下所示,但我无法弄清楚如何对元描述内容执行类似的操作。
<h1 id="pagetitle"></h1>
<script>
document.getElementById('pagetitle').innerHTML = document.title;
</script>
I would prefer to find a PHP solution for this (and for the page title, too, for that matter).我更愿意为此找到一个 PHP 解决方案(以及页面标题,就此而言)。 but I'd also be happy also to do this using JavaScript.
但我也很乐意使用 JavaScript 来做到这一点。
You can select a <meta name="description">
element with a meta[name=description]
selector:您可以使用
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>
Also remember to only use innerHTML
when deliberately inserting HTML markup - if you only want to insert text, use textContent
instead.还记得在故意插入 HTML 标记时只使用
innerHTML
- 如果您只想插入文本,请改用textContent
。 ( innerHTML
is less appropriate, slower, and can allow for arbitrary code execution if the content being set isn't trustworthy) (
innerHTML
不太合适,速度较慢,如果设置的内容innerHTML
则可以允许任意代码执行)
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.