HTML DOM Base 对象


HTML DOM Base 对象与 HTML <base> 元素关联。<base> 元素用于指定 HTML 文档中所有其他 URL 的基准 URL。HTML 文档中最多只能有一个 <base> 元素。Base 对象用于设置或获取 <base> 元素的 href 属性。

属性

以下是 Base 对象的属性:

属性描述
href设置或返回 base 元素中 href 属性的值
target设置或返回 base 元素中 target 属性的值

语法

以下是语法:

创建 base 元素:

document.createElement ("base")

访问 base 元素:

var a = document.getElementById("demoBase");

示例

让我们来看一个 base 对象的示例:

<!DOCTYPE html>
<html>
<body>
<p>Create the element first and then access it</p>
<p>Click the button below to create or access BASE element.</p>
<button onclick="CreateBase()">CREATE</button>
<button onclick="AcessBase()">ACCESS</button>
<p id="SAMPLE"></p>
<script>
   function CreateBase() {
      var x = document.createElement("BASE");
      x.setAttribute("id","myBase");
      x.setAttribute("href", "https://www.google.com");
      document.head.appendChild(x);
      document.getElementById("SAMPLE").innerHTML = "BASE element with href
      https://www.google.com is created";
   }
   function AcessBase() {
      var x = document.getElementById("myBase").href;
      document.getElementById("SAMPLE").innerHTML = x;
   }
</script>
</body>
</html>

输出

这将产生以下输出:

点击“创建”后:

点击“访问”后:

在上面的示例中:

我们创建了两个按钮“创建”和“访问”,分别执行 CreateBase() 和 AccessBase() 函数。

<button onclick="CreateBase()">CREATE</button>
<button onclick="AcessBase()">ACCESS</button>

CreateBase() 函数创建一个 base 元素并将其赋值给变量 x。然后使用 setAttribute() 方法设置其 id 和 href。新创建的 base 元素随后使用 appendChild() 属性附加到文档头部。最后,base 创建消息显示在与其关联的 id 为 SAMPLE 的段落中。

function CreateBase() {
   var x = document.createElement("BASE");
   x.setAttribute("id","myBase");
   x.setAttribute("href", "https://www.google.com");
   document.head.appendChild(x);
   document.getElementById("SAMPLE").innerHTML = "BASE element with href https://www.google.com is created";
}

AcessBase() 函数用于访问我们新创建的 <base> 元素。它通过按 id 获取元素,然后获取其 href 值并将其赋值给名为 x 的变量。然后将 x 中的信息显示在 id 为 SAMPLE 的段落中。

function AcessBase() {
   var x = document.getElementById("myBase").href;
   document.getElementById("SAMPLE").innerHTML = x;
}

更新于:2019年8月6日

浏览量:112

启动你的职业生涯

完成课程获得认证

开始学习
广告
© . All rights reserved.