[英]How do I change the title of a web page using javascript?
I know this is a duplicate question, but I've tried a few approaches and I'm not able to get the solution I need. 我知道这是一个重复的问题,但是我尝试了几种方法,但无法获得所需的解决方案。 I need to change the title of a web page, and I thought Javascript would be a good candidate.
我需要更改网页的标题,并且我认为Javascript是一个不错的选择。 I've read many disapproving comments already, talking about how changing the title will negatively affect SEO-I'm not worried about that just now.
我已经读过许多不赞成的评论,谈论更改标题将如何对SEO产生负面影响-我现在并不担心。 I'm able to change the title by reassigning a value in an inline script:
我可以通过在嵌入式脚本中重新分配值来更改标题:
<input type="button" value="Click me." onclick="document.title = 'Some new title';" />
But using an inline script in this case is out of the question. 但是在这种情况下使用内联脚本是不可能的。 I tried loading an embedded script tag above & below the body of the script, no go.
我尝试在脚本主体的上方和下方加载嵌入式脚本标签,不行。 This is what I settled on, and it didn't work initially (keep reading):
这是我所确定的,并且最初没有起作用(请继续阅读):
<script>
document.addEventListener("load", function changeTitle(){
document.title = "FUBAR";
}, true);
</script>
I've tried adding/removing the 'true' value at the end of the parameter list and that doesn't change anything. 我已经尝试在参数列表的末尾添加/删除“ true”值,并且它没有任何改变。 I avoided naming the function, then named it, and that didn't change anything.
我避免命名该函数,然后对其命名,但这并没有改变任何内容。 What DID work was changing "load" to "click".
DID所做的工作是将“负载”更改为“点击”。 I need the title to change right after the document is finished loading...is there something else I can use, like "ready", or "onload"?
我需要在文档加载完成后立即更改标题...还有其他可以使用的东西,例如“ ready”或“ onload”吗? Using "load" yielded no results, but I swear I've seen it used before.
使用“负载”不会产生任何结果,但是我发誓我以前曾经看过它。
Thanks! 谢谢!
Try using window.addEventListener
rather than document.addEventListener
尝试使用
window.addEventListener
而不是document.addEventListener
See https://developer.mozilla.org/en-US/docs/Web/Events/load 参见https://developer.mozilla.org/en-US/docs/Web/Events/load
Note: More reliable is to add event listener on "window.addEventListener".
注意:更可靠的方法是在“ window.addEventListener”上添加事件侦听器。
No need to wait for the load
event. 无需等待
load
事件。 Just set the title: 只需设置标题:
<html>
<head></head>
<body>
<script>document.title = "foobar"</script>
<!-- rest of document -->
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.