简体   繁体   English

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

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

I have a set of DIVs, each contains an image with an empty anchor tag wrapped around it 我有一组DIV,每个DIV都包含一个图像,该图像周围包裹着一个空的锚标签

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

I then have a 'Continue reading' link just before the div closes 然后在div关闭之前我有一个“继续阅读”链接

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

Is there a way with jQuery that when the page loads, I can that the href location of the continue reading button and apply that the empty anchor wrapped around my image? jQuery是否有办法在页面加载时使继续阅读按钮的href位置适用于将空锚包裹在图像上?

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

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

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

It is possible, but it is not a good idea. 有可能,但这不是一个好主意。 Links created with js are not visible for google crawers. 用js创建的链接对Google爬虫不可见。 The right way of doing this is creating a real link instead of "#". 正确的方法是创建一个真实的链接,而不是“#”。

Do the things right not interesting ;). 把事情做对不有趣;)。

based on your HTML, you can do this: 根据您的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
    });
})​​

You can loop through the "continue reading" links and copy their href, perhaps like this: 您可以遍历“继续阅读”链接并复制其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"));
});​

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

The :contains selector that I used above is not going to be the most efficient way to do it, but it works. 我上面使用的:contains选择器并不是实现它的最有效方法,但是它可以工作。 If it were my html I'd probably give those "continue reading" anchor elements a common class and select on that. 如果是我的html,我可能会给那些“继续阅读”锚定元素一个普通的类,然后选择它。 Or you could select the "meta-nav" spans and then take their parent. 或者,您可以选择“元导航”跨度,然后选择其父级。 (Lots of options, really.) (确实有很多选择。)

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

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