简体   繁体   English

JavaScript整个div链接,目标为“ _blank”

[英]Javascript entire div link WITH target=“_blank”

I have set up a div with a button link. 我已经设置了带有按钮链接的div。 I have my javascript set up so if someone clicks anyway in the div, it will use the link text. 我已经设置了我的JavaScript,因此如果有人在div中单击仍然会使用链接文本。 Here's my current code: 这是我当前的代码:

 jQuery(function($){
 $(".entire-div-link").click(function() {
 window.location = $(this).find("a").attr("href"); 
 return false;
 });
 });

This works awesome, but the links still open in the current tab, and not in a new tab like I'd like. 这很棒,但是链接仍在当前选项卡中打开,而不是在我希望的新选项卡中打开。 Is there an easy code correction I can use? 我可以使用简单的代码更正吗?

I'd suggest using a tag as a block instead of div: 我建议使用a标签作为一个块,而不是DIV:

//css
.block-link {
  display: block;
}

// html
<a class="block-link" target="_blank">
  ...
</a>

https://jsfiddle.net/kjugdpnf/ https://jsfiddle.net/kjugdpnf/

Try window.open instead of window.location . 尝试使用window.open而不是window.location

https://jsfiddle.net/nimittshah/t4wnsrkh/ https://jsfiddle.net/nimittshah/t4wnsrkh/

Just do this, it's way shorter with plain JS: 只需执行此操作,使用普通JS就会更短:

document.querySelector(".entire-div-link").addEventListener("click", ()=>{
  window.open = "URL HERE"
})

As it was already mentioned, whether window.open will open a new tab OR a new window, depends solely on the user's browser configuration. 如前所述, window.open将打开一个新选项卡还是一个新窗口,仅取决于用户的浏览器配置。

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

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