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;
}
廣告
資料結構
網路
關係資料庫管理系統 (RDBMS)
作業系統
Java
iOS
HTML
CSS
Android
Python
C語言程式設計
C++
C#
MongoDB
MySQL
Javascript
PHP