我有<div>文字。此文本包含 URL。
<div id="text">
text,text, https://static01.nyt.com/images/2021/09/14/science/07CAT-STRIPES/07CAT-STRIPES-mediumSquareAt3X-v2.jpg
</div>
<script>
$('#text').each(function() {
var exp = /(\b[^"'](https?|ftp|file):\/\/[-A-Z0-9 &@#\/%?=~_|!:,.;]*[-A-Z0-9 &@#\/%=~_|])/ig;
})
</script>
問題是:如何獲取URL并將其放入<img src="here">?
uj5u.com熱心網友回復:
您可以使用match從文本中獲取 URL,然后將其添加為src任何影像的屬性。
$('#text').each(function() {
var exp = /((https?|ftp|file):\/\/[-A-Z0-9 &@#\/%?=~_|!:,.;]*[-A-Z0-9 &@#\/%=~_|])/ig
// Find the URL in the div
const urls = $(this).text().match(exp)
// Loop through the URLs
for (let i = 0; i < urls.length; i ) {
// As an example, we're setting the img src that corrosponds to the
// current index
$('img').eq(i).attr('src', urls[i])
}
})
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div id="text">
text,text, https://static01.nyt.com/images/2021/09/14/science/07CAT-STRIPES/07CAT-STRIPES-mediumSquareAt3X-v2.jpg, text, https://static01.nyt.com/images/2021/09/14/science/07CAT-STRIPES/07CAT-STRIPES-mediumSquareAt3X-v2.jpg
</div>
<img>
<img>
轉載請註明出處,本文鏈接:https://www.uj5u.com/yidong/392409.html
標籤:查询
上一篇:帶有方括號的“getElementsByClassName()[]”代碼?它有什么作用?如何將其轉換為jQuery?[復制]
