繁体   English   中英

获取链接href并将其应用于另一个jQuery链接

[英]Get link href and apply it to another link jQuery

我有一组DIV,每个DIV都包含一个图像,该图像周围包裹着一个空的锚标签

<a href="#"> Image is here </a>

然后在div关闭之前我有一个“继续阅读”链接

<a href="?p=453">Continue reading <span class="meta-nav">→</span></a>

jQuery是否有办法在页面加载时使继续阅读按钮的href位置适用于将空锚包裹在图像上?

演示: http : //jsfiddle.net/2hu66/1/

$('.card-prod').each(function() {
    var cr = $(this).find('a:last');
    $(this).find('.cardclick').attr('href', cr.attr('href'));
});

提琴示例: http : //jsfiddle.net/2hu66/4/

有可能,但这不是一个好主意。 用js创建的链接对Google爬虫不可见。 正确的方法是创建一个真实的链接,而不是“#”。

把事情做对不有趣;)。

根据您的HTML,您可以执行以下操作:

​$(function(){
    $('.card-prod').each(function(){                         //for each item
        var theLink = $('a[href^="?p"]',this).attr('href');  //get the link
        $('a.cardclick',this).attr({'href':theLink});        //set to img link
    });
})​​

您可以遍历“继续阅读”链接并复制其href,也许是这样的:

​$(​"div.card-prod a:contains('Continue reading')")​​​​​​​​​​​​​​​​​​​​​​​​​​.each(function() {
    var $this = $(this);
    $this.closest("div.card-prod")
         .find("a.cardclick")
         .attr("href", $this.attr("href"));
});​

更新的演示: http : //jsfiddle.net/2hu66/3/

我上面使用的:contains选择器并不是实现它的最有效方法,但是它可以工作。 如果是我的html,我可能会给那些“继续阅读”锚定元素一个普通的类,然后选择它。 或者,您可以选择“元导航”跨度,然后选择其父级。 (确实有很多选择。)

暂无
暂无

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

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