簡體   English   中英

如何通過jQuery從某些元素獲取文本的一部分

[英]How to get the part of text from some element via jquery

我想把文本放在第一個li里面:

<li data-type="course" value="1">
   This Is Some Course
   <ul class="submenu-widget" style="">
      <li data-type="section" value="3">&nbsp;- This Is Some Section
      </li>
      <li data-type="section" value="4">&nbsp;- This Is Another Section
      </li>
      <li data-type="section" value="5">&nbsp;- This Is Some Section - Copy
      </li>
      <li data-type="section" value="8">&nbsp;- This Is Some Section - Copy - Copy
      </li>
      <li data-type="section" value="9">&nbsp;- This Is Some Section - Copy
      </li>
      <li data-type="section" value="10">&nbsp;- This Is Some Section - Copy
      </li>
      <li data-type="section" value="11">&nbsp;- This Is Some Section - Copy
      </li>
      <li data-type="section" value="12">&nbsp;- This Is Some Section - Copy
      </li>
      <li data-type="section" value="13">&nbsp;- This Is Some Section - Copy
      </li>
   </ul>
</li>

我試過了 :

var course_name = ui.item.parent().parent().text();

但是它也返回所有部分的文本。但是我希望它返回“ This Is Some Course”。

工作提琴

您可以使用:first選擇器:

$('.submenu-widget li:first').text();

如果您想把li放在外面,可以使用data屬性選擇它:

$("li[data-type='course']").text();

希望這可以幫助。

如果您只想獲取文本“ This Is Some Course”,請使用:

$.trim( $('li[data-type="course"]').clone().children().remove().end().text() )

jsFiddle示例

如果使用此:

$("li[data-type='course']").text();

您將獲得輸入字段的文本,其中包含“ This is some Course”

試試這個

jQuery("body>ul>li").contents()
  .filter(function() {
  return this.nodeType === 3;
}).text()

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM