Jquery打开新标签页(_blank)

7

我根据其他StackOverflow问题/答案设置了一些基于Jquery的内容。这个脚本的目的是,通过在div内部任何a href标签上设置链接,将整个div成为一个链接。

这个工作正常,但是我需要将它设置为_blank,在新标签中打开。我已经尝试了以下方式,但没有成功。

$(document).ready(function() {
    $(".product-item").click(function() {
        $(this).target = "_blank";
        window.location = $(this).find("a").attr("href");
        return false;
    });
});

编辑

感谢帮助,但这些答案都不起作用。如果有人能够粘贴真正有效的完整代码,而不是没有测试是否有效的小片段。谢谢。

编辑2

感谢kristinalim提供完整的可行解决方案。


这个问题以前已经有了答案:https://dev59.com/bnE85IYBdhLWcg3wVR-g - Ulises
window.location 始终 指的是当前窗口的位置。更改它将影响当前窗口。 - techfoobar
$(".product-item").click(function(){ $(this).find("a").attr("href"); window.open(this); return false;
});
- user2085752
4个回答

23

在页面上设置链接需要结合@Ravi和@ncksllvn的答案:

// Find link in $(".product-item") and set "target" attribute to "_blank".
$(this).find("a").attr("target", "_blank");

如需在新窗口中打开页面,请参阅此问题:jQuery click _blank,对于自定义选项,请参阅此引用中的window.open

更新:

您需要类似于以下内容:

$(document).ready(function() {
  $(".product-item").click(function() {
    var productLink = $(this).find("a");

    productLink.attr("target", "_blank");
    window.open(productLink.attr("href"));

    return false;
  });
});

请注意使用.attr()的方法:

$element.attr("attribute_name")                   // Get value of attribute.
$element.attr("attribute_name", attribute_value)  // Set value of attribute.

嗨,Kristina,这似乎进展顺利。你能看一下下面的代码并告诉我有什么问题吗? - user2085752
$(document).ready(function(){ $(".product-item").click(function(){ $(this).find("a").target = "_blank"; window.open(this.href); return false;
}); });
- user2085752
谢谢Kristina,那个方法可行。完整回答问题获得10分 :) - user2085752
对我有用 :) 谢谢 - PC.
正是我所需要的,谢谢! - crystallove18

3

请替换这一行:

$(this).target = "_blank";

使用:

$( this ).attr( 'target', '_blank' );

这将把它的HREF设置为_blank。


1

1

您不能将target属性设置为div,因为div不知道如何处理HTTP请求。 相反,您可以为链接标签设置target属性。

$(this).find("a").target = "_blank";
window.location= $(this).find("a").attr("href")

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接