在字符串中提取特定标记的文本

时间:2018-04-24 13:47:40

标签: jquery html find

我在p标签中有一些文字。我想提取第一个img标记文本。

<p>Lorem ipsum dolor sit amet, <img width ="50" src ="djdjdj.jpg"></img>consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, <img width ="50" src ="sfdsfdsfdsf.jpg"></img>quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat. Duis aute irure dolor in reprehenderit in voluptate velit esse cillum dolore eu fugiat nulla pariatur. Excepteur sint occaecat cupidatat non proident, sunt in culpa qui officia deserunt mollit anim id est laborum.</p>

所以我想要的结果是:

<img width ="50" src ="djdjdj.jpg"></img>

我试过

 $("p").find("img").text()  

但它不起作用。

1 个答案:

答案 0 :(得分:0)

我在Chrome上对此进行了测试,并且可以正常运行:

&#13;
&#13;
console.log($("p img:first")[0].valueOf());
&#13;
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>

<p>Lorem ipsum dolor sit amet, <img width="50" src="djdjdj.jpg"></img>consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, <img width="50" src="sfdsfdsfdsf.jpg"></img>quis nostrud exercitation
  ullamco laboris nisi ut aliquip ex ea commodo consequat. Duis aute irure dolor in reprehenderit in voluptate velit esse cillum dolore eu fugiat nulla pariatur. Excepteur sint occaecat cupidatat non proident, sunt in culpa qui officia deserunt mollit
  anim id est laborum.</p>
&#13;
&#13;
&#13;