简体   繁体   English

jQuery / Json-如何获得最后一个 <P> 在这个JSON对象中?

[英]Jquery/Json - How can I get the last <P> in this JSON object?

The usual .last or :last jquery selectors are not doing it for me. 普通的.last或:last jQuery选择器对我来说不是这样。 I have an object content.object that has HTML in it like 我有一个对象content.object有HTML

<P>
item 1
</P>
<P>
item 2
</P>
<P>
item 3
</P>

I have tried 我努力了

var lastItem = $(content.object).find('p:last');

and

var lastItem = $(content.object).find('p').last();

But these aren't doing the trick and I keep getting errors. 但是这些并没有解决问题,而且我不断出错。 How can I get the text in the last 我怎样才能得到最后的文本

?

The find method wont work because you are already inside the same depth as the p tags find方法将无法正常工作,因为您已经位于与p tags相同的深度内

If your JSON object looks like this 如果您的JSON对象看起来像这样

var content = {
    object: '<P>item 1</P><P>item 2</P><P>item 3</P>'
};

You can access the last p like so: 您可以像这样访问最后一个p:

var lastItem = $( content.object ).last();

You need to use filter 您需要使用过滤器

var lastItem = $(content.object).filter('p:last');

.filter : Reduce the set of matched elements to those that match the selector or pass the function's test. .filter :将匹配元素的集合减少到与选择器匹配或通过功能测试的元素。 .find : Get the descendants of each element in the current set of matched elements, filtered by a selector, jQuery object, or element. .find :获取当前匹配元素集中每个元素的后代,由选择器,jQuery对象或元素过滤。

Demo: Fiddle 演示: 小提琴

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

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