给定一个HTML文档,如何使用JavaScript创建链接,并将其添加到文档中?下面本篇文章就来给大家介绍一下在HTML中使用JavaScript创建链接的方法,希望对大家有所帮助。
image
做法:
● 创建一个锚<a>元素。
● 创建一个文本节点,其中包含一些将显示为链接的文本。
● 将文本节点附加到锚<a>元素。
● 设置<a>元素的title和href属性。
● 在body中追加<a>元素。
示例1:使用appendChild()方法将锚a元素添加到正文
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
</head>
<body style="text-align:center;">
<p style="font-size: 19px; font-weight: bold;">单击按钮,可使用JavaScript生成链接</p>
<button onclick="Fun()">点击这里</button>
<p id="DOWN" style="color: green; font-size: 24px; font-weight: bold;"></p>
<script>
var el_down = document.getElementById("DOWN");
function Fun() {
var a = document.createElement('a');
//为锚a元素创建文本节点
var link = document.createTextNode("这是链接!");
// 将文本节点追加到锚a元素
a.appendChild(link);
// 设置title.
a.title = "这是链接!";
// 设置href属性
a.href = "https://www.html.cn";
// 将锚元素附加到body
document.body.appendChild(a);
}
</script>
</body>
</html>
效果图:
1.gif
示例2:使用prepend()方法将锚a元素添加到正文
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
</head>
<body style="text-align:center;">
<p style="font-size: 19px; font-weight: bold;">单击按钮,可使用JavaScript生成链接</p>
<button onclick="Fun()">点击这里</button>
<p id="DOWN" style="color: green; font-size: 24px; font-weight: bold;"></p>
<script>
var el_down = document.getElementById("DOWN");
function Fun() {
var a = document.createElement('a');
//为锚a元素创建文本节点
var link = document.createTextNode("这是链接!");
// 将文本节点追加到锚a元素
a.appendChild(link);
// 设置title.
a.title = "这是链接!";
// 设置href属性
a.href = "https://www.html.cn";
// 将锚元素附加到body
document.body.prepend(a);
}
</script>
</body>
</html>
效果图:
2.gif