javascript document.write() removes the html from page and display result in a blank page [duplicate]

爱⌒轻易说出口 提交于 2019-12-04 02:42:41

问题


Possible Duplicate:
JavaScript - what are alternatives to document.write?

i am creating a javascript function which i want to execute after few seconds but when it executes it removes all the page content and display only that result which i am displaying using document.write() here is my javascript code.

<script language="javascript">
if (window.XMLHttpRequest)
{// code for IE7+, Firefox, Chrome, Opera, Safari
 xmlhttp=new XMLHttpRequest();
}
else
{// code for IE6, IE5
 xmlhttp=new ActiveXObject("Microsoft.XMLHTTP");
}

setTimeout(function(){
xmlhttp.open("GET","some.xml",false);
xmlhttp.send();
xmlDoc=xmlhttp.responseXML;
var x=xmlDoc.getElementsByTagName("offer");
var page = parseInt(x.length) / 10;
document.write("<div class='pagination_btn_cont'>");
for (i=1;i<=page;i++)
{ 
 document.write("<div class='pagination_btn'>"+i+"</div>");
}
document.write("</div>");
},10000);

</script>

when i open the webpage its display all the content of the page but after 10 seconds the page will become blank and display only the numbers which i am getting from the loop.

any suggestion how can do this task.


回答1:


You can use innerHTML in javascript. It use to insert data to particular div without affecting page contents.

Example:

var results = "";
for(var i=1;i<=10;i++)
{
     results += "<div class='pagination_btn'>"+i+"</div>";
}
document.getElementById("your result show div id").innerHTML = results;

you can specify $('.pagination_btn').bind("click")... inside your document.ready




回答2:


Use innerHtml to change text of a specific element.

HTML

<div id="container"></div>

javascript

document.getElementById('container').innerHTML += '<div>content</div>';

or you can use jQuery library, life will be much easier:

$("#container").append("<div>content</div>");



回答3:


try this

document.getElementsByTagName('body').innerHTML += '<div id="parent" class="pagination_btn_cont">';

for (i=1;i<=page;i++)
{ 
 document.getElementById('parent').innerHTML = "<div class='pagination_btn'>"+i+"</div>";
}


来源:https://stackoverflow.com/questions/12669314/javascript-document-write-removes-the-html-from-page-and-display-result-in-a-b

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!