【问题标题】:href attribute of anchor element changed automatically锚元素的 href 属性自动改变
【发布时间】:2012-09-13 13:29:05
【问题描述】:

我正在尝试访问 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 属性为何以及如何自动更改。

谁能解释一下这个问题?

【问题讨论】:

  • &lt;a&gt; 元素在哪里?您正在使用 /myservlet?myParam=foobar! 覆盖 HTML 内容
  • 对不起,我写错了参数。我已经更正了有问题的更改。感谢您的评论。
  • console.log() 输出什么?

标签: javascript html tags anchor


【解决方案1】:

链接元素上的href 属性是一个特殊属性,而不是简单的字符串。它可能会将您的 href 值更改为它认为可以解析的绝对 URL。您可以使用getAttribute 获取未更改的值。

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

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2022-08-08
    • 1970-01-01
    • 2021-10-31
    • 2018-05-21
    • 2011-08-30
    • 1970-01-01
    • 1970-01-01
    • 2021-12-19
    相关资源
    最近更新 更多