简体   繁体   中英

How can I open a link in a new tab if it has target=_blank?

I am trying to open a link in a new tab only if that link has a target=_blank like so.

<a href="https://google.com" target="_blank">Google</a>

For some reason the target=_blank is not working in the a Bootstrap 4.5 navbar Therefore, I am trying to use jQuery to get it to work as some links have the target=_blank attribute:

$('a.navigation-title').click(function () { 
    location.href = this.href; 
    $(this).find('a').attr('target','_blank'); 
    window.open(this.href, '_blank'); 
  });

That's the script I've used, but its not having any effect.

Change code to

<a href="https://google.com" class="navigation-title" target="_blank">Google</a>

I have added a new class to the 'a' tag for triggering the click event for jquery

$('.navigation-title').click(function () { 
    var url = $(this).attr('href'); 
    window.open(url , '_blank'); 
  });

 var elements = document.querySelectorAll('a[target=_blank]'); for (var index = 0; index < elements.length; index++) { const element = elements[index]; element.addEventListener('click', function (e) { e.preventDefault(); var href = element.getAttribute('href'); if (href) { window.open(href, '_blank'); } return false; }); }
 <a href="https://google.com" target="_blank">Google</a>

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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