admin管理员组

文章数量:1416072

I am trying to create a link by means of the tag "a", click this link and open it in a new tab. My script works but does not open the link in a new tab does it on the same page.

The script is activated by clicking on the "body" element of the web page. Apparently the target = '_blank' is not working.

<script>
function openInNewTab(url) {
    var a = document.createElement("a");
    a.target = '_blank';
    a.href = window.location.href;
    a.click();
    window.location.href = '';
    }

$("body").click(function () {
openInNewTab();
});
</script>

I am trying to create a link by means of the tag "a", click this link and open it in a new tab. My script works but does not open the link in a new tab does it on the same page.

The script is activated by clicking on the "body" element of the web page. Apparently the target = '_blank' is not working.

<script>
function openInNewTab(url) {
    var a = document.createElement("a");
    a.target = '_blank';
    a.href = window.location.href;
    a.click();
    window.location.href = 'https://www.google..pe';
    }

$("body").click(function () {
openInNewTab();
});
</script>
Share Improve this question asked Jun 12, 2017 at 3:37 KokoxKokox 5191 gold badge11 silver badges25 bronze badges 1
  • Possible duplicate of How to open a URL in a new Tab using javascript or jquery? – Mark Commented Jun 12, 2017 at 3:45
Add a ment  | 

4 Answers 4

Reset to default 2

change your line

a.target = '_blank';

to

a.setAttribute('target', '_blank');

Just use window.open(url,'_blank'); with target blank parameter .

function openInNewTab(url) {
	window.open(url, '_blank');
    }

$("body").click(function () {	

url='https://www.google..pe/';
openInNewTab(url);
});
<script src="https://ajax.googleapis./ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<body>
	
	
	<h1>body</h1>
</body>

window.open('https://www.google..pe', 'name'); 
  • 'name' is a name of the window. Following names are supported
  • _blank - URL is loaded into a new tab. This is a default.
  • _parent - URL is loaded into the parent frame _self - URL replaces the current page
$(document).on('click', 'a', function(e){ 
    e.preventDefault(); 
    var url = $(this).attr('href'); 
    window.open(url, '_blank');
});

本文标签: jqueryJavascriptCreate a quotaquot element and open it in a new tabStack Overflow