我试图在2秒(2000毫秒)后动态更改页面的标题。
这是我尝试过的代码:
<!DOCTYPE HTML> <html> <head> <title>Before</title> </head> <body onload="updateTitle"> <script> var title = document.getElementsByTagName('title'); function updateTitle() { //Here is some kind of delay (of 2 seconds). I have tried setTimeout(), setInterval() and delay() title.innerHTML = "After"; </script> Dummy Content for Body </body> </html>如何修改以便在2秒后页面标题发生变化?
I am trying to dynamically change the title of a page after 2 seconds (2000 ms).
Here is the code I have tried:
<!DOCTYPE HTML> <html> <head> <title>Before</title> </head> <body onload="updateTitle"> <script> var title = document.getElementsByTagName('title'); function updateTitle() { //Here is some kind of delay (of 2 seconds). I have tried setTimeout(), setInterval() and delay() title.innerHTML = "After"; </script> Dummy Content for Body </body> </html>How might this be modified so that after 2 seconds, the page title changes?
最满意答案
要更改标题,您应该使用window.title
window.title = 'After';万一,你绝对必须使用document.getElementsByTagName ,注意它返回一个元素数组 ,第一个你需要使用。 即
document.getElementsByTagName('title')[0].innerHTML = 'After';当然,如果页面没有<title>元素,则上述操作将导致错误。 第一个( window.alert )将适用于任何一种情况。
延迟
为了引入延迟,您可以使用setTimeout (就像您已经完成的那样)
<script> function updateTitle() { setTimeout(function() { window.title = 'After'; }, 2000); } </script>整页工作代码 :
请注意,包含updateTitle()的块已移至。 问题是当浏览器试图将它绑定到onload (在解析页面时)时,函数updateTitle()尚未定义 - 因为它是在体内进行的。
<!DOCTYPE html> <html> <head> <title>Before</title> <script> function updateTitle() { setTimeout(function() { document.getElementsByTagName('title')[0].innerHTML = 'After'; }, 2000); } </script> </head> <body onload="updateTitle()"> Dummy Content for Body </body> </html>For changing the title, you should rather be using window.title
window.title = 'After';In case, you absolutely must use document.getElementsByTagName, note that it returns an array of elements, the first of which you need to make use of. i.e.
document.getElementsByTagName('title')[0].innerHTML = 'After';Of course, if the page does not have a <title> element, the above will result in an error. The first one (window.alert) will work in either case.
Delay
For introducing the delay, you can use setTimeout (as you've already done)
<script> function updateTitle() { setTimeout(function() { window.title = 'After'; }, 2000); } </script>Full page working code:
Notice that the block containing updateTitle() has been moved to the . The issue was that the function updateTitle() was not yet defined when the browser tried to bind it to onload (while parsing the page) - as it was defined afterwards inside the body.
<!DOCTYPE html> <html> <head> <title>Before</title> <script> function updateTitle() { setTimeout(function() { document.getElementsByTagName('title')[0].innerHTML = 'After'; }, 2000); } </script> </head> <body onload="updateTitle()"> Dummy Content for Body </body> </html>更多推荐
发布评论