Jquery 添加到在新标签页中打开的链接

Jquery add to links to open in new tab

我正在帮助一个客户使用他们的 WooCommerce WordPress 网站,当您在产品 image/link 在新选项卡中打开的类别页面上单击产品时,他们希望拥有它。我一直在尝试使用 jquery 来添加它,但没有成功。我是 jquery 的新手,希望得到任何帮助。

HTML:

<ul class="products">
    <li class="post-6568 product type-product status-publish has-post-thumbnail first sale shipping-taxable purchasable product-type-simple product-cat-designer-watch-special product-tag-tw-steel instock">   <a href="http://harmonyjewellers.ca/product/tw-steel-7823/">

        <img src="http://harmonyjewellers.ca/wp-content/uploads/2014/11/7823595-400x400.jpg" class="attachment-shop_catalog wp-post-image" alt="78235" height="400" width="400">
        <h3>TW Steel (#7823)</h3>



    <span class="price"><del><span class="amount">,190.00</span></del> <ins><span class="amount">4.00</span></ins></span>

    </a>

    </li>
</ul>

jQuery:

$(document).ready(function () {

    var productLinks = $('ul.products img').find('a');
    prodcutLinks.click(function () {
        $(this).attr("target", "_blank");

    });

});

JSFiddle:https://jsfiddle.net/6nbc6zj8/

你不需要 jquery...只需将它添加到你的 link 本身:<a href="#" target="_blank"><img></a>

https://jsfiddle.net/6nbc6zj8/1/

<ul class="products">
    <li class="post-6568 product type-product status-publish has-post-thumbnail first sale shipping-taxable purchasable product-type-simple product-cat-designer-watch-special product-tag-tw-steel instock">   
        <a href="http://harmonyjewellers.ca/product/tw-steel-7823/" target="_blank">            
            <img src="http://harmonyjewellers.ca/wp-content/uploads/2014/11/7823595-400x400.jpg" class="attachment-shop_catalog wp-post-image" alt="78235" height="400" width="400"/>
            <h3>TW Steel (#7823)</h3>            
            <span class="price">
                <del><span class="amount">,190.00</span></del> 
                <ins><span class="amount">4.00</span></ins>
            </span>                       
        </a>        
    </li>
</ul>

编辑:如果您不能更改 html,那么您想这样做:https://jsfiddle.net/6nbc6zj8/7/

$(document).ready(function () {
    $('.products li a').attr('target', '_blank');
});

你的目标是 products li a 元素,只是在它们上面添加属性。您当前的代码仅在点击时添加它,但您想在点击前添加属性。

你已经有了一个很好的答案,你的问题可能不清楚,但如果你真的想用jQuery来做,我建议这样:

https://jsfiddle.net/6nbc6zj8/8

$(document).ready(function () {


    $('ul.products img').click(function () {
        var productLinks = $(this).closest('a').attr('href');
        window.open(productLinks, '_blank');
        window.focus();

    });

});