我要做的就是使標題與 h1 標簽完全相同。
<title class="blogtitle"></title>
<h1 class="title">Updating our staff members</h1>
<script>
document.getElementsByClassName("blogtitle")[0].innerHTML = h1;
var h1 = document.getElementsByClassName("title")
</script>
uj5u.com熱心網友回復:
這對 SEO 和可訪問性都非常不利。不要為此使用 JS。使用允許在服務器上執行此操作的模板引擎。
話雖如此,如果搜索引擎優化或可訪問性與您的專案有任何相關性,那么您不應該使用可以執行此操作的 Javascript。
document.addEventListener('DOMContentLoaded', // make sure this code only runs once JS can access the DOM safely
function() { //
document.title = document.querySelector('h1.title')?.textContent ?? '';
}
);
<!DOCTYPE html>
<html lang="en">
<head>
<title></title>
</head>
<body>
<h1 class="title">Updating our staff members</h1>
</body>
</html>
除了使用DOMContentLoaded偵聽器(僅用于確保頁面中的所有元素都可以通過 Javascript 訪問),您還可以<script>在結束標記之前包含您的</body>標記:
<!DOCTYPE html>
<html lang="en">
<head>
<title></title>
</head>
<body>
<h1 class="title">Updating our staff members</h1>
<script>
document.title = document.querySelector('h1.title')?.textContent ?? '';
</script>
</body>
</html>
uj5u.com熱心網友回復:
好吧,看起來您只是在學習 HTML 并進入這個新世界。所以我只會回答你的問題,而不是用一堆高級資訊讓你超負荷。
您可以使用更改頁面標題
document.title = 'Your new title'
所以你可以按照以下方式做一些事情:
var h1Element = document.getElementsByClassName("title")[0] // you can use other selectors here such as querySelector, getElementByClassName...
var h1Text = h1Element.innerHTML
document.title = h1Text
此外,您不應該將類放入標題標簽中,它必須在<head>標簽內。
只需記住 HTML 的基本結構:
<!DOCTYPE html>
<html>
<head>
<title>Page Title</title>
</head>
<body>
<h1>My First Heading</h1>
<p>My first paragraph.</p>
</body>
</html>
轉載請註明出處,本文鏈接:https://www.uj5u.com/shujuku/411144.html
標籤:
下一篇:三秒鐘后清除頁面上的所有內容
