简体   繁体   中英

How to replace all img tags in HTML string with <a><img></a>?

I have HTML string and I open it in UIWebView. Now, I want to make all my images clickable, to put them into link tags like:

Was:

<img src="..." />

Became:

<a href="..."><img src="..." /></a>

Is there any easy solution?

I've tried to find all tags and replace them inside of the string, but it was very painful.

I've tried that:

let js = "var a=document.createElement('a');a.href='http://mylink.com';var image = document.getElementById('mydiv').getElementsByTagName('img')[0];b=a.appendChild(image);document.getElementById('mydiv').appendChild(a);"

self.webView.stringByEvaluatingJavaScriptFromString(js)

but it did not help me

Short answer: No, there is not an easy solution. Don't do that. Trying to parse and change HTML source from a client app is a horrible idea, and will always be very painful. It's kind of like trying to perform brain surgery on yourself with a sawzall, a mirror, and some old dental tools.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM