使用jQuery,如何获取li元素的“内部文本”?

3

我有以下html代码,我正在试图找出正确的选择器逻辑来读取其中的某些部分。 注意:由于这是由插件生成的,所以我无法更改html代码。

  <li class="select2-selection__choice" title="">
      <span class="select2-selection__choice__remove" role="presentation">×</span>
    MS Office
 </li>
 <li class="select2-selection__choice" title="">
      <span class="select2-selection__choice__remove" role="presentation">×</span>
    Photoshop
 </li>

我正在尝试读取

标签内的文本。
 <li class="select2-selection__choice">

但不包括

 <span class="select2-selection__choice__remove">

所以对于上面的例子,我希望解析出以下文本:

 MS Office, Photoshop

@WhiteHat - 我没有选择,因为这个HTML是由插件生成的,所以这就是我得到的(因此提出了问题)。 - leora
2个回答

2
试试这样做。
$('.select2-selection__choice').each(function() {
    var text = $(this).clone().children().remove().end().text();
    console.log(text.trim());
});

片段

$('.select2-selection__choice').each(function() {
    var text = $(this).clone().children().remove().end().text();
    console.log(text.trim());
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<li class="select2-selection__choice" title="">
      <span class="select2-selection__choice__remove" role="presentation">×</span>
    MS Office
 </li>
 <li class="select2-selection__choice" title="">
      <span class="select2-selection__choice__remove" role="presentation">×</span>
    Photoshop
 </li>


这个解决方案似乎包括在select2-selection__choice__remove span中的"x",而我不想包括它。 - leora
请检查控制台而非 HTML。 - Anik Islam Abhi
3
请提供解释,而非仅仅代码。 - Anid Monsur

1
使用 .class 选择器:
$('.select2-selection__choice').each(function() {
    var inneText = $(this).children().text();        
});

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接