添加 target="_blank" 以与 JavaScript 链接

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/6822945/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-25 21:58:08  来源:igfitidea点击:

Add target="_blank" to link with JavaScript

javascript

提问by Paul

I need to write a method that takes a String and parses it for links (a href). If it finds a link it should add target="_blank" to the link, if it is not already there.

我需要编写一个方法,它接受一个字符串并将其解析为链接(a href)。如果它找到一个链接,它应该将 target="_blank" 添加到链接中,如果它还没有的话。

Example: The Inputstring "

示例:输入字符串“

 <a href="www.google.com">Google</a> and <a href="www.yahoo.com"> target="_blank">Yahoo</a> are search engines

... should result in the output String

...应该导致输出字符串

<a href="www.google.com" target="_blank">Google</a> and <a href="www.yahoo.com" target="_blank">Yahoo</a> are search engines

Any idea how to realize this?

知道如何实现这一点吗?

回答by timw4mail

Not very difficult with plain js.

使用普通 js 并不是很困难。

var links = document.getElementsByTagName('a');
var len = links.length;

for(var i=0; i<len; i++)
{
   links[i].target = "_blank";
}

回答by maerics

Fraught with problems but usable with plain JavaScript:

充满问题,但可以使用纯 JavaScript:

function addBlankTargets(s) {
  return (""+s).replace(/<a\s+href=/gi, '<a target="_blank" href=');
}

Or with jQuery:

或者使用 jQuery:

function addBlankTargets(s) {
  var p = $('<p>' + s + '</p>');
  p.find('a').attr('target', '_blank');
  return p.html();
}
var s = '<a href="www.google.com">Google</a> and '
      + '<a href="www.yahoo.com">Yahoo</a> '
      + 'are search engines.';
var x = addBlankTargets(s);
x; // => '<a href="www.google.com" target="_blank">Google</a> and
   //     <a href="www.yahoo.com" target="_blank">Yahoo</a>
   //     are search engines.'

回答by Toni Bianchetti

If you are targeting at modern browsers, instead of manipulating a string containing HTML and having to handle all the many special cases, you can transform the string into DOM. At this point manipulating the DOM is trivial and you can then convert it back to a serialised string.

如果您的目标是现代浏览器,您可以将字符串转换为 DOM,而不是操作包含 HTML 的字符串并且必须处理所有许多特殊情况。此时操作 DOM 是微不足道的,然后您可以将其转换回序列化字符串。

function decorateRichText(html) {
  const domParser = new DOMParser()
  const document = domParser.parseFromString(html, `text/html`)
  const serializer = new XMLSerializer()

  // Handles external links
  const links = document.querySelectorAll(`a`)

  links.forEach((link) => {
    if (link.href) {
      if (isExternalUrl(link.href)) {
        link.target = `_blank`
        link.rel = `noopener noreferrer`
      }
    }
  })

  return serializer.serializeToString(document)
}

Leave the browser JS engine do the heavy stuff and remember: code that you don't write is code you have not to debug :-)

让浏览器 JS 引擎做繁重的工作,记住:你不写的代码是你不必调试的代码 :-)

回答by ghayes

You can use jQuery to parse the element, add the attribute, and then read out the HTML, like so:

您可以使用 jQuery 解析元素,添加属性,然后读出 HTML,如下所示:

 var addTarget = function(input) {
   return $('<span>' + input + '</span>').find('a').attr('target', '_blank').html();
 };

 console.log(addTarget('<a href="www.google.com">Google</a>'));

回答by iLevi

in two lines

在两行

var links = document.getElementsByTagName('a');
for(i in links)
    links[i].target=="_blank"?links[i].style.color="#f0f" : links[i].style.color ='#0f0'

jsfiddle

提琴手