如何使用jQuery在给定元素之前获取文本? [英] How to get a text before given element using jQuery?

查看:89
本文介绍了如何使用jQuery在给定元素之前获取文本?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

让我们考虑以下html代码:

Let's consider following html code:

<p>
  Some text followed by <span>a span element</span>
  and another text followed by <b>a bold text</b>.
</p>

如何使用jQuery获取spanb元素之前的文本?

How can I get the text before the span and b elements using jQuery?

我尝试了$("span").prev()$("b").prev(),但是它确实起作用了,因为文本不是元素.我也尝试过$("span").parent(),但是它与整个段落匹配,而我只希望其中一部分.

I tried $("span").prev() and $("b").prev() but it did work because the text is not an element. I also tried $("span").parent() but it matched whole paragraph, while I want only a part of it.

您能提出任何解决方案吗?预先谢谢您:-)

Could you advise any solution? Thank you in advance :-)

推荐答案

如何将它们收集到数组中,而不是两次调用$:

How about collecting them into an array instead of two calls to $:

var texts = $('span, b').map(function(){
    return this.previousSibling.nodeValue
});
texts[0]; // "Some text followed by "
texts[1]; // " and another text followed by "

参考文献:

  • The previousSibling property
  • jQuery.map

这篇关于如何使用jQuery在给定元素之前获取文本?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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