String.prototype.anchor()

已棄用:此特性不再推薦。雖然某些瀏覽器可能仍然支援它,但它可能已經從相關的網路標準中刪除,可能正在刪除過程中,或者可能僅為相容性目的而保留。請避免使用它,如果可能,請更新現有程式碼;請參閱本頁底部的相容性表格以指導您的決策。請注意,此特性可能隨時停止工作。

String 值的 anchor() 方法會建立一個字串,該字串將此字串嵌入到一個帶有 name<a> 元素中(<a name="...">str</a>)。

注意: 所有 HTML 包裝器方法 都已棄用,僅為相容性而標準化。請使用 DOM API,例如 document.createElement()

HTML 規範已不再允許 <a> 元素具有 name 屬性,因此此方法甚至無法生成有效的標記。

語法

js
anchor(name)

引數

name

一個字串,表示要放入生成的 <a name="..."> 開始標記中的 name 值。

返回值

一個字串,以 <a name="name"> 開始標記(name 中的雙引號會被替換為 &quot;)開頭,然後是文字 str,最後是 </a> 結束標記。

示例

使用 anchor()

下面的程式碼建立了一個 HTML 字串,然後用它替換文件的正文。

js
const contentString = "Hello, world";

document.body.innerHTML = contentString.anchor("hello");

這將建立以下 HTML

html
<a name="hello">Hello, world</a>

警告: 此標記無效,因為 name 已不再是 <a> 元素的有效屬性。

與其使用 anchor() 直接建立 HTML 文字,不如使用 DOM API,例如 document.createElement()。例如:

js
const contentString = "Hello, world";
const elem = document.createElement("a");
elem.innerText = contentString;
document.body.appendChild(elem);

規範

規範
ECMAScript® 2026 語言規範
# sec-string.prototype.anchor

瀏覽器相容性

另見