2017-10-17 31 views
-2

美好的一天,我試圖用ckeditor來製作文章內容。這是我輸入的一個例子。是否可以使用jQuery或JavaScript從文本中提取圖像?

<p>I have two images&nbsp;<img alt="" src="http://localhost:84/lf//assets/images/commingsoon.png" style="height:225px; width:225px" />&nbsp;and this&nbsp;&nbsp;<img alt="" src="http://localhost:84/lf//assets/images/article2.jpg" style="height:91px; width:122px" /></p> 

正如你可以看到有兩個圖像,我想第一個圖像作爲我的縮略圖。現在,我只想提取它。

從提取的結果是這樣的

http://localhost:84/lf//assets/images/commingsoon.png 

var myString = '<p>I have two images&nbsp;<img alt="" src="http://localhost:84/lf//assets/images/commingsoon.png" style="height:225px; width:225px" />&nbsp;and this&nbsp;&nbsp;<img alt="" src="http://localhost:84/lf//assets/images/article2.jpg" style="height:91px; width:122px" /></p>'; 
var result = (someprosess) 
+2

您是否嘗試過這個$(IMG).attr( 'SRC'); –

+0

欲瞭解更多信息,請首先設置一個'img'變量。 'var img = $(「img」)[0]'會抓住第一張圖片,'[1]'會抓住第二張圖片。然後你可以做'var imgSrc = $(img).attr(「src」)'。 – Naltroc

回答

0

您可以使用find(),first()attr()訪問字符串中第一個圖像的URL。

var myString = '<p>I have two images&nbsp;<img alt="" src="http://localhost:84/lf//assets/images/commingsoon.png" style="height:225px; width:225px" />&nbsp;and this&nbsp;&nbsp;<img alt="" src="http://localhost:84/lf//assets/images/article2.jpg" style="height:91px; width:122px" /></p>'; 
 
var result = $(myString).find('img').first().attr('src'); 
 
console.log(result);
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>

0

您可以使用JavaScriptjQuery搜索圖像的第一個實例,解析出其SRC

作爲一個例子,使用jQuery(如果內容中總是會有圖像)

var imgPointer = $('body').find('img'); 
var imgSrc = imgPointer[0].attr('src'); 
0

在這裏你去使用jQuery

console.log($('p').find('img:first').attr('src'));
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> 
 
<p>I have two images&nbsp;<img alt="" src="http://localhost:84/lf//assets/images/commingsoon.png" style="height:225px; width:225px" />&nbsp;and this&nbsp;&nbsp;<img alt="" src="http://localhost:84/lf//assets/images/article2.jpg" style="height:91px; width:122px" /></p>

希望這會幫助你解決。

相關問題