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

javascript - How to make a div onload function? - Stack Overflow

programmeradmin1浏览0评论

I want to load an HTML page as a div inside my webpage by removing its HTML and body tags. But the HTML page has a <body onload=" ... " > , I need this function to continue working. Seems <div onload=" ... " > is not working. How can I insert this onload function into my website's body (on this page only) without directly editing my original website code (php)?

I want to load an HTML page as a div inside my webpage by removing its HTML and body tags. But the HTML page has a <body onload=" ... " > , I need this function to continue working. Seems <div onload=" ... " > is not working. How can I insert this onload function into my website's body (on this page only) without directly editing my original website code (php)?

Share Improve this question edited Dec 14, 2011 at 6:15 Nightfirecat 11.6k6 gold badges37 silver badges53 bronze badges asked Dec 14, 2011 at 6:11 JennyJenny 1,7275 gold badges19 silver badges38 bronze badges 0
Add a comment  | 

5 Answers 5

Reset to default 7

Have you used jQuery before? If so, just get the id of your div (let's say "SomeDiv") and then use the "ready" method like this:

$("#SomeDiv").ready(
function(){
     //do stuff
    });

you can use jQuery.load to load the contents of the page into your div

$(document).ready(function() {
  $("#containing-div").load("[url of page with onload function]");
});

the code above goes in the page that contains the div. the page with the onload function doesn't get changed.

You can add an additional Javascript tag at the end of the loaded page (once inserted inside the div) which will executing as soon as it's loaded. Like this:

<div>
    Insert the inner html content of that pages here and add this script at the bottom and add the onload function of the original html to this script.
    <script type="javascript">
       alert("hello world");
    </script>
</div>

Just remember to have the javascript available to your page. What I mean is that if the javascript function called which is called inside onload="..." is defined in the <head> of the loading html document and you're throwing the <head> out then this won't work.

Not the best but one way is to check the div periodically if it's loaded:

var myInterval = setInterval(function () {
if ($('.mydiv') && $('.mydiv').width() > 0) {
// write your logic here
clearInterval(myInterval);
    } 
}, 3000);

If you want to add the onload event on a div, you cannot, but you can add onkeydown and trigger the onkeydown event on document load.

<div onkeydown="setCss();"></div>

$(function () {
    $(".ccsdvCotentPS").trigger("onkeydown");
});
发布评论

评论列表(0)

  1. 暂无评论