【发布时间】:2014-02-13 04:59:44
【问题描述】:
所以我试图显示一个被 Javascript 捕获的 url。它以http://i.mygreatsite.com 的形式返回给 JS,但我想切断架构以使其更清晰,并让实际代码看起来像
<a href=http://i.mygreatsite.com>i.mygreatsite.com</a>
在我尝试这样做之前,我必须在 url 上设置一些特殊属性,即将目标设置为空白,以便它可以在新选项卡中打开并将超链接的颜色更改为黑色,就像其他链接一样页面是蓝色的。我是这样处理的:
init: function() {
this.on("success", function(file, responseText) {
var span = document.createElement('span');
var a = document.createElement('a');
a.href = responseText;
a.innerHTML = responseText;
a.setAttribute('target', '_blank');
a.style.color="black";
span.appendChild(a);
span.setAttribute("style", "position: absolute; box-sizing: border-box; -webkit-box-sizing: border-box; bottom: -28px; left: 3px; right: 3px; height: 28px; word-wrap: break-word; line-height: 28px; text-overflow: ellipsis; ");
file.previewTemplate.appendChild(span);
});
}
一切正常,但是当我去删除架构时,我使用正则表达式做到了:
repl = responseText.replace(/(https?:\/\/(\S+))/i, "<a href='$1'>$2</a>");
a.href = repl;
a.innerHTML = repl;
a.setAttribute('target', '_blank');
a.style.color="black";
现在模式已被删除,但我之前设置的所有属性现在都不存在了。 URL 为蓝色并在同一选项卡中打开。我在这里错过了什么吗?谢谢。
【问题讨论】:
-
不知道为什么会出现这种奇怪的行为,可能是因为您同时为 href 和 innerhtml 设置了标签。正则表达式很有趣,但在这种情况下,为什么不将 href 设置为原始响应文本,因为这是链接的 URL,而将 innerhtml 设置为 responsetext.slice(8,responsetext.length)
-
我还需要它来删除 http://,而不仅仅是 https://
-
ah k,尽管我认为问题在于您在字符串中制作了完整的标签。我认为您需要将 href 设置为 URL = 'h ttp://i.mygreatsite.com' 并将 innerHTML 设置为替换文本'i.mygreatsite.com'。你现在的做法是将它们都设置为: i.mygreatsite.com 所以你得到一个非常奇怪的结构,可能是一个 href 标签href 标记,浏览器会尝试以可能出乎意料的方式理解这一点