jquery:如何找到在当前元素之前出现2个元素的元素 [英] jquery: how to find an element which is coming 2 elements before current element

查看:203
本文介绍了jquery:如何找到在当前元素之前出现2个元素的元素的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个看起来像这样的标记:

i have a markup which look like this:

<h3>Paragraf3-dummytext</h3>
<p>
<a name="paragraf3">
Quisque id odio. Praesent venenatis metus at tortor pulvinar varius. Lorem ipsum dolor sit 
</a>
</p>

我想要做的是找到所有带有'name'属性的'a'标签并找到该锚点的'h3'标签;我试图这样做:

what i want to do is to find all 'a' tags with 'name' attribute and find the 'h3' tag for that anchor; im trying to do it like this:

var paragraf = [];
var paragrafheading = [];
$('a[name]').each(function() {
paragraf.push($(this).attr('name'));
paragrafheading.push($(this).prev().text());

但它不起作用,因为有文本周围的'p'标签。

but it does not work because there is a 'p' tag around the text.

推荐答案

你可以这样做:

paragrafheading.push($(this).parent().prev().text());

如果a周围没有段落,或者你不知道锚点在h3之前有多少父母,你可以这样做:

If there's not always paragraph around the a, or you don't know how many parents the anchor can have before the h3, you can do something like this:

paragrafheading.push($(this).closest('> h3').find('> h3').text());

这篇关于jquery:如何找到在当前元素之前出现2个元素的元素的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆