首页 > 解决方案 > 当 Div 名称不唯一时,使用 jQuery 从 Div 中获取文本

问题描述

有没有办法根据它的位置来获取 div 的文本内容?

    <div class="locationDetailsRight">
   <div class="shiptoexpanded">
      <div>3 / 15</div>
      <div group-key="Shipping 12/2/2020">
         <div class="shipSort">20201202</div>
         12/2/2020
      </div>
      <div group-key="">$53.11</div>
      <div group-key="">$159.33</div>
      <div group-key="">$11.10</div>
      <div group-key="">$170.43</div>
   </div>
</div>

我想抢 159.33 美元和 170.43 美元。

我写的:

console.log($(".locationDetailsRight .shiptoexpanded").text())

回来:

    "
          3 / 15
          
             20201202
             12/2/2020
          
          $53.11
          $159.33
          $11.10
          $170.43

"

是否可以在我需要的行中获取文本?

标签: javascripthtmljquery

解决方案


使用第 n 个子选择器https://api.jquery.com/nth-child-selector/

对于您的代码,以下将起作用

alert($(".shiptoexpanded").find(':nth-child(4)').text());
alert($(".shiptoexpanded").find(':nth-child(6)').text());

这是JSFiddle

https://jsfiddle.net/eqam8vbg/1/


推荐阅读