【问题标题】:How to style hyperlink after scheme is removed with Javascript?使用 Javascript 删除方案后如何设置超链接样式?
【发布时间】: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 标记,浏览器会尝试以可能出乎意料的方式理解这一点

标签: javascript url-rewriting


【解决方案1】:

你最终得到的是另一个锚中的锚:

<a target="_blank" style="XXX"><a href="http://myurl">myurl</a></a>

这是因为设置了您要创建的锚点的innerHTML。在元素上设置样式不会级联(您应该真正使用 CSS 样式表),当然 target 元素将不适用,因为它在技术上不是您单击的超链接!

相反,只需使用您的正则表达式的$2 结果设置innerHTML

编辑

所以您更新的代码需要类似于:

repl = responseText.replace(/(https?:\/\/(\S+))/i, "$2");
a.href = responseText;
a.innerHTML = repl;
a.setAttribute('target', '_blank');
a.style.color="black";
//Or if you wanted to use CSS stylesheets
a.className = "myCssClass"

【讨论】:

猜你喜欢
  • 2013-12-02
  • 2011-03-24
  • 1970-01-01
  • 2012-02-13
  • 2011-01-15
  • 1970-01-01
  • 2020-08-18
  • 1970-01-01
  • 2017-03-20
相关资源
最近更新 更多