1

所以我的页面上有这个 html:

<div class='item'>
    <h2><a href='http://www.mysite.com/1'>Link 1</a></h2>
    <p class='desc'>Text text text text</p>
</div>

<div class='item'>
    <h2><a href='http://www.mysite.com/2'>Link 2</a></h2>
    <p class='desc'>Text text text text</p>
</div>

<div class='item'>
    <h2><a href='http://www.mysite.com/3'>Link 3</a></h2>
    <p class='desc'>Text text text text</p>
</div>

我想使用同级 h2 标记中的链接在段落末尾附加一个链接。我有这个 jQuery:

$('p.desc').append(' <a href="' + $(this).prev().find('a').attr('href') + '">More ></a>');

但是链接只是设置为undefined. 我在这里做错了什么?

4

3 回答 3

2

为了能够获得相对于每个元素的值,然后创建一个锚标记,您不能像您一样简单地链接操作。需要进行某种迭代,以便您可以确定每个特定段落的范围并获取相关链接。大多数时候你可以使用each它,但append碰巧支持一个函数作为它的参数,然后它需要返回你将添加到每个元素的内容。在此上下文中,您可以解析 h2 的链接是什么并返回新的锚点。

$('p.desc').append(function() { // loop through all p.desc and add something
    // within this function, $(this) is now the current p.desc
    var link = $(this).prev('h2').find('a').attr('href'); // get the path
    return $('<a/>').attr('href', link).text('More'); // return the new link
});

您显然不必费心创建link变量,我只是讨厌长行代码,并认为这样更容易弄清楚发生了什么。

于 2013-05-03T21:29:26.437 回答
1
$('.desc').append(function(
    return $(this).prev('h2').find('a').clone().text('More >');
});
于 2013-05-03T21:28:00.363 回答
0

问题是您使用$(this),它没有按照您想要的方式应用范围,因为您将它作为参数传递给 append 方法,基本上将您的范围嵌套在没有锚标记的地方 - 因此您得到了“未定义”的不希望的结果。通过使用“每个”,您可以正确地为您正在使用的当前代码分配范围,只需将其包装在一个匿名函数中,如下所示:

$('p.desc').each(function(){
    // Your code here
});
于 2013-05-03T22:02:10.553 回答