锚点元素的href属性自动更改

href attribute of anchor element changed automatically

本文关键字:属性 href 元素      更新时间:2023-09-26

我试图访问HTML <a>元素的href属性,但不知何故,该值会自动更改。

以下是我的代码:

function getTDElement(anchorString)
{
  var td = document.createElement('td');
  // i think this is not a good way to add child to html element but 
  // i have to do it for some unavoidable reason
  td.innerHTML = anchorString;
  var anchor = td.firstChild;
  // following line prints url like
  // http://localhost/myservlet?myParam=foobar
  console.log(anchor.href);
  return td;
}
// im passing only /myservlet?myParam=foobar in following line
getTDElement("<a href=/myservlet?myParam=foobar>display</a>");

我无法理解元素的href属性为什么以及如何自动更改。

有人能谈谈这个问题吗?

链接元素的href属性是一个特殊的属性,而不是一个简单的字符串。它可能会将您的href值更改为它认为解析到的绝对URL。您可以使用getAttribute获得未更改的值。
console.log(anchor.getAttribute('href'));