最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

javascript - JS: body tag onload equivalent? - Stack Overflow

programmeradmin3浏览0评论

I need to basically add this to my page:

<body onload="document.getElementById('WeddingBandBuilder').focus()">

However due to my template I cannot change the tag. So is there a way to do the equivalent with a script in the < head > tag or something?

Thanks!

I need to basically add this to my page:

<body onload="document.getElementById('WeddingBandBuilder').focus()">

However due to my template I cannot change the tag. So is there a way to do the equivalent with a script in the < head > tag or something?

Thanks!

Share asked May 21, 2009 at 14:50 JD IsaacksJD Isaacks 58k96 gold badges279 silver badges431 bronze badges
Add a ment  | 

4 Answers 4

Reset to default 8
<script>
window.onload = function() {document.getElementById('WeddingBandBuilder').focus()};
</script>

You should always be careful there isn't already a window.onload defined. I've been burned a number of times by assuming I would be the only one attaching things to <body onload="..."> or window.onload.

See this answer and ments for a solution to this issue.

Use a JS library like jQuery or Prototype and create an external script file with something like this:

for jQuery:

$(function() { $('#WeddingBandBuilder').focus(); });

for Prototype:

Event.observe(window, 'load', function() { $('WeddingBandBuilder').focus(); });

I might check if that page has already included jQuery? If so, you can do something like this:

$(document).ready(function() {
    $('#WeddingBandBuilder').focus();
});
发布评论

评论列表(0)

  1. 暂无评论