jquery - Javascript - Create a "a" element and open it in a new tab - Stack Overflow

I am trying to create a link by means of the tag "a", click this link and open it in a new ta

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

发布者:admin,转转请注明出处:http://www.yc00.com/questions/1745246349a4618428.html

相关推荐

发表回复

评论列表(0条)

  • 暂无评论

联系我们

400-800-8888

在线咨询: QQ交谈

邮件:admin@example.com

工作时间:周一至周五,9:30-18:30,节假日休息

关注微信