简体   繁体   English

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

[英]Add target=“_blank” to link with JavaScript

I need to write a method that takes a String and parses it for links (a href).我需要编写一个方法,该方法接受一个字符串并将其解析为链接(a href)。 If it finds a link it should add target="_blank" to the link, if it is not already there.如果它找到了一个链接,它应该将 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?知道如何实现这一点吗?

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

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.'

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.如果您的目标是现代浏览器,您可以将字符串转换为 DOM,而不是操作包含 HTML 的字符串并且必须处理所有许多特殊情况。 At this point manipulating the DOM is trivial and you can then convert it back to a serialised string.此时操作 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 引擎做繁重的工作,记住:你不写的代码是你不必调试的代码 :-)

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

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提琴手

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

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