[英]Replace html string to img tag with pure javascript
我希望javascript執行此操作:
根據div中的單詞,我希望將字符串替換為img標簽。
如果我有
<div id="example" style="align-content: right; text-align: right">abc</div>
與`
<div id="example" style="align-content: right; text-align: right"><img src="example123.html"></div>`
但僅當div內是文本/字符串“ abc”時
另一種情況,如果我有
<div id="example" style="align-content: right; text-align: right">def</div>
我想轉換成這個
<div id="example" style="align-content: right; text-align: right"><img src="anotherexample.html"></div>
與第一種情況類似,如果文本為“ def”,則替換為另一個img。
我已經用jQuery完成了
這是我在jquery中完成的代碼
$("#example:contains('abc')").html(function (_, html) {return html.replace(/abc/g, "<img src=example123.html>")});
$("#example:contains('def')").html(function (_, html) {return html.replace(/def/g, "<img src=anotherexample.html>")});
這很容易做到,但是我在工作中使用jquery時遇到了一些問題,因此我不能也不應使用jquery或其他框架。 如果它是用純JavaScript完成的,那就太好了。
我幾乎忘記了使用條件句(特別是Swith)會很棒,我認為使用switch而不是其他方式可以減少糾結
預先感謝您的回答。
PD:如果您問我為什么需要解決這個問題,原因是我正在使用一個生成pdf文件的應用程序,該文件會從DB中提取數據,並根據文本,用具有特定URL的圖片替換。
因為您使用的是具有特定id
的元素,所以它是唯一的-您只需選擇該元素並檢查其innerHTML
包含您要查找的字符串即可。 您可以使用正則表達式將abc
或def
所有實例替換為適當的標記:
const example = document.querySelector('#example'); const srcs = { abc: 'example123', def: 'anotherexample' }; example.innerHTML = example.innerHTML.replace( /abc|def/g, prop => `<img src="${srcs[prop]}">` );
<div id="example" style="align-content: right; text-align: right">before abc after</div>
嘗試這個。 它遍歷所有div
元素並使用textContent
檢查其text
。如果匹配,則使用innerHTML
用image標簽替換文本。
var a = document.querySelectorAll('div'); a.forEach((e) => { if (e.textContent == "abc") e.innerHTML = "<img src='example123.com'>" if(e.textContent == "def") e.innerHTML = "<img src='anotherexample.com'>" })
<div id="example" style="align-content: right; text-align: right">abc</div> <div id="example" style="align-content: right; text-align: right">def</div>
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.