简体   繁体   English

锚元素的href属性自动更改

[英]href attribute of anchor element changed automatically

I am trying to access href attribute of HTML <a> element but somehow that value gets changed automatically. 我正在尝试访问HTML <a>元素的href属性,但是不知何故该值会自动更改。

Following is my code : 以下是我的代码:

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>");

I am not able to understand why and how href attribute of element changes automatically. 我无法理解元素的href属性为何以及如何自动更改。

Can anyone please shed some light on this issue? 谁能说明这个问题?

The href property on a link element is a special property, not a simple string. 链接元素上的href属性是一个特殊属性,而不是简单的字符串。 It is liable to change your href value to the absolute URL it thinks it resolves to. 可以将href值更改为它认为解析的绝对URL。 You can get the unchanged value using getAttribute . 您可以使用getAttribute获得不变的值。

console.log(anchor.getAttribute('href'));

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM