String.prototype.anchor() 是一個早期 JavaScript 方法,用於生成帶有 name 屬性的 HTML 錨點標籤 ``。該方法已從 Web 標準中移除,僅為兼容性保留,現代開發不推薦使用。本文僅作歷史認識與維舊代碼參考。
string.anchor(anchorName)
name 屬性值<a name="anchorName">string</a>
var str = new String("Hello world");
var anchorHTML = str.anchor("myanchor");
console.log(anchorHTML);
// 輸出: <a name="myanchor">Hello world</a>
document.body.innerHTML =
'內容區域...' +
'章節1'.anchor('section1') +
'章節2'.anchor('section2') +
'章節3'.anchor('section3');
// 配合鏈接跳轉
// <a href="#section1">跳轉到章節1</a>
| 原因 | 說明 |
|---|---|
| 非標準 | 從未納入 ECMAScript 標準,屬於 Netscape 早期擴展 |
| 語義錯誤 | HTML5 建議用 id 替代 name 作為錨點標識 |
| 混淆結構與行為 | JS 生成 HTML 字符串違反關注點分離,難以維護 |
| XSS 風險 | 若 anchorName 來自用戶輸入未轉義,易導致注入 |
| 現代替代完善 | 模板字符串、框架虛擬 DOM、原生 DOM API 更安全可控 |
function createAnchor(text, name) {
return `<a id="${escapeHtml(name)}">${escapeHtml(text)}</a>`;
}
function escapeHtml(str) {
return str.replace(/[&<>"']/g, c => ({'&':'&','<':'<','>':'>','"':'"',"'":'''}[c]));
}
function createAnchorElement(text, id) {
const a = document.createElement('a');
a.id = id;
a.textContent = text; // 自動轉義
return a;
}
// 使用
document.body.appendChild(createAnchorElement('章節1', 'section1'));
// Vue
<a :id="anchorName">{{ text }}</a>
// React
<a id={anchorName}>{text}</a>
<html>
<head><title>JavaScript String anchor() Method</title></head>
<body>
<script>
var str = new String("Hello world");
alert(str.anchor("myanchor")); // 彈出: Hello world
</script>
</body>
</html>
anchor() 生成 `` 標籤字符串,已棄用id 屬性作為錨點目標:`