这是我目前提出的代码。它填写正确的标题,但页面标题匹配时页面不可见。我该如何解决这个问题?什么是正确的方式"如果是页面标题,执行此代码"?
<head>
<title>Page Name 1</title>
</head>
<body>
<style>
#notavailablemsg {
font-size: 30px;
color: #f04e37;
display: inline;
}
#notavailablemsg div {
display: inline;
visibility: hidden;
}
#submsg {
font-size: 22px;
visibility: hidden;
}
#pagename {
font-style: italic;
}
</style>
<center>
<div id="notavailablemsg">
<div>The page </div>
<br>
<div id="pagename">page title</div>
<div> no longer exists</div>
</div>
<div id="submsg">
We are sorry for the inconvenience.
</div>
</center>
<script>
var errortitle = document.getElementsByTagName("title")[0].innerHTML;
document.getElementById("pagename").innerHTML = errortitle;
</script>
<script>
if (errortitle == "Page Name 1") {
document.getElementByID("notavailablemsg").innerHTML.style.visibility = "visible";
document.getElementByID("submsg").innerHTML.style.visibility = "visible";
}
</script>
</body>
</html>
@Midas回答:修改为
document.getElementById("notavailablemsg").style.visibility = "visible";
document.getElementById("submsg").style.visibility = "visible";
答案 0 :(得分:0)
您可以使用document.title获取当前标题。
实施例
<!DOCTYPE html>
<html>
<head>
<title>YourGoodTitle</title>
<style>
div {
border: 1px solid red;
width: 100%;
height: 50px;
display: none; /* its good to use display: none to hide elements*/
}
</style>
</head>
<body onload="myFunction()">
<h1>Hello World!</h1>
<center>
<div id="notavailablemsg">
Bad title
</div>
<div id="availablemsg">
Glad you are here
</div>
</center>
<script>
function myFunction() {
var title = document.title;
if( title == "YourGoodTitle" ) {
// select and make elements visible
document.getElementById( "availablemsg" ).style.display = "block";
} else {
// hide the elements you want, make their display = none;
// for example
document.getElementById( "availablemsg" ).style.display = "none";
// show your expected elements
document.getElementById( "notavailablemsg" ).style.display = "block";
}
}
</script>
</body>
</html>
https://plnkr.co/edit/KS2obzXrUqtzT8FWUvwL?p=preview
因此,如果您的标题是 YourGoodTitle ,则会显示YourGoodTitle消息。否则将打印错误标题