简体   繁体   中英

Other elements disapper after page is loaded?

I want call function javascript with Jquery. But after page is loaded, all other elements are disappeared. You can see my code here. I need your fix.

<script src='http://code.jquery.com/jquery-1.10.1.min.js'></script>
<script type="text/javascript">
$(document).ready(function() {
$("#recentpost").each(function(){
mytext = "Food";
sticky();
});
});
</script>

<script type="text/javascript">
function sticky(){
document.write("<div class='sample'>"+mytext+"</div>");
}
</script>
<div id="recentpost"></div>

<div>something here disappear after loaded page</div>

Thank for your help

It's because you're using document.write after the page is loaded, which writes the new content to the document, effectively destroying the page.

You should be using the DOM to manipulate content, as all the HTML has been written and parsed into an object tree.

For example,

function sticky(){
    document.getElementById("recentpost").textContent = mytext;
}

Also, it's odd that you're using .each() on an ID. There can be only one on the page.

So instead of this:

$("#recentpost").each(function(){
    mytext = "Food";
    sticky();
});

You'd do this:

$("#recentpost").text("Food");

Or if you wanted to use your sticky() function, you should pass the value to the function instead of using a global variable.

sticky("Food");

function sticky(mytext) {
    $("#recentpost").text(mytext);
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM