繁体   English   中英

JavaScript动态链接问题?

[英]Javascript dynamic link issues?

可能有重复的内容(我尝试过检查有关创建动态链接的问题,但它们引用的是静态链接-我希望对用户隐藏此链接)。 在ww3网站上测试以下代码时:

<!DOCTYPE html>
<html>
<body>

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

</body>
</html>

我得到:

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

作为链接地址,而不是www.google.com。

我该如何解决这个问题? 以及如何使链接仅在设置的时间后出现? 请注意,这是代码的简化版本,以提高可读性(动态链接将包括在运行脚本时分配的两个浮点变量)。

<a>标记的href必须包含协议http:// ,否则它链接到相对于链接所在页面的文档:

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

document.write()的用例通常是有限的,因为在页面加载后不能覆盖整个内容而不能使用它。 很多时候,您需要在页面呈现后创建元素。 在这种情况下,您将使用document.createElement()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);

顺便说一下,w3schools不隶属于W3C ,并且通常不建议使用它们的示例,因为它们经常过时或不完整。

您有2个问题:

1)您需要在URL之前添加http:// ,以便它是: http : //www.google.com 2)您不需要在document.write中使用引号,但是如果您愿意,可以使用以下三种方法之一:

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>");

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

要使链接绝对,请在URL的开头包含“ http://”。 写出:

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

代替

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

第二个示例将被视为相对网址,例如index.html

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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