简体   繁体   中英

Javascript dynamic link issues?

There might be a duplicate of this (I've tried checking questions on creating dynamic links but they reference a static link - I want this link to be hidden from the user). On testing the following code on the ww3 site:

<!DOCTYPE html>
<html>
<body>

<script type="text/javascript">
document.write("<a href=&quot;www.google.com&quot;>Google</a>");
</script>

</body>
</html>

I get:

 http://www.w3schools.com/jsref/%22www.google.com%22

As the link address rather than www.google.com.

How do I correct this problem? And how do I make it so the link only appears after a set time? Note, this is a simplified version of the code for readability (the dynamic link will including two floating point variables assigned at the time the script is run).

An <a> tag's href must include the protocol http:// , otherwise it links to a document relative to the page the link is on:

// Print quote literals, not html entities `&quot;`
document.write("<a href='http://www.google.com'>Google</a>");

The use cases for document.write() are often limited since it can't be used after the page has loaded without overwriting the whole thing. A lot of the time you will want to create the element after the page has already rendered. In that case, you would use document.createElement() and appendChild() .

// Create the node...
var newlink = document.createElement('a');
newlink.href = 'http://www.google.com';
// Set the link's text:
newlink.innerText = "Google";

// And add it to the appropriate place in the DOM
// This just sticks it onto the <body>
// You might, for example, instead select a specific <span> or <div>
// by its id with document.getElementById()
document.body.appendChild(newlink);

By the way, w3schools is not affiliated with the W3C , and their examples are generally not recommended since they are often out of date or incomplete.

You have 2 issues:

1) You need http:// before the URL so it's: http://www.google.com 2) You don't need to use quotes in document.write, but if you want to you can do one of these 3:

document.write('<a href="http://www.google.com">Google</a>');
document.write("<a href='http://www.google.com'>Google</a>");
document.write("<a href=http://www.google.com>Google</a>");

使用斜杠“ \\”转义引号

To make the link absolute, include the "http://" at the start of the url. Write out:

<a href="http://www.google.com">

instead of

<a href="www.google.com">

The second example will be treated as a relative url, like index.html for example.

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