开发者

document.write in html/php doc writes to new page

开发者 https://www.devze.com 2023-04-07 01:32 出处:网络
I\'m trying to write a piece of text over an existing web page based on whether or not the cookie is set. The cookie part works fine, but the d开发者_运维技巧ocument.write causes the text to appear on

I'm trying to write a piece of text over an existing web page based on whether or not the cookie is set. The cookie part works fine, but the d开发者_运维技巧ocument.write causes the text to appear on a new blank page.

<script type="text/javascript">
function getCookie(c_name)
{
var i,x,y,ARRcookies=document.cookie.split(";");
for (i=0;i<ARRcookies.length;i++)
{
x=ARRcookies[i].substr(0,ARRcookies[i].indexOf("="));
y=ARRcookies[i].substr(ARRcookies[i].indexOf("=")+1);
x=x.replace(/^\s+|\s+$/g,"");
if (x==c_name)
{
return unescape(y);
}
}
}

function setCookie(c_name,value,exdays)
{
var exdate=new Date();
exdate.setDate(exdate.getDate() + exdays);
var c_value=escape(value) + ((exdays==null) ? "" : "; expires="+exdate.toUTCString());
document.cookie=c_name + "=" + c_value;
}

function checkCookie()
{
var username=getCookie("username");
if (username!=null && username!="")
{
alert("Welcome again " + username);
}
else
{
username=prompt("Please enter your name:","");
document.write ("hello"); 
if (username!=null && username!="")
{
setCookie("username",username,7);

}
}
}
</script>


<body onload="checkCookie()">

</body>

I guess I need to use a z-index somehow, but can't seem to get it to work. If someone could explain how I get my 'document.write' line to appea on top of the stuff that already exists on the page, I would be really grateful. All of this is happening on a page on a joomla site, and the code is in the php file for one of the modules. Thanks all.

Rob.


Assign the body an ID, such as 'body', then use the following:

document.getElementById('body').innerHTML = 'Text that you want to assign';

W3 Schools has a good example of it.


document.write() should be avoided.

It has few (arguably) valid use cases, all of which must be used inline in a script element and executed as the page is loaded.

When you use it beyond the page load, it will implicitly call document.open() which will clear your page.

You should favour modern standardised DOM methods.


I think you should define a part in your Markup, where the message should be added.

<div id="wrapper">
<div id="message"></div>
<div id="content">
...
</div>
</div>

So you can just add your Message into the "message"-div:

document.getElementById('message').innerHTML = 'Hello '+username;
0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号