![](/img/trans.png)
[英]How can I add an HTML element after another one in javascript?
[英]How can I convert one html element to another element?
最近一直在寫微信小程序。
有一些 HTML 字符串會從遠程服務器獲取(這些字符串也被網站使用,所以它必須通過 JavaScript 轉換)並渲染到小程序的主體中。
而微信小程序不能接受我必須轉換的HTML字符串。
例如,HTML 字符串如下所示:
<div>
<h2 id="Title">Here is a H2</h2>
<article class="ContentArticle">
There are some articles.
</article>
</div>
我必須像這樣轉換它們:
<view class="div">
<text class="Title h2">Here is a H2</text>
<text class="ContentArticle article">
There are some articles.
</text>
</view>
在我的第一個意見中,我考慮通過String.replace
方法來實現這一點。 但是,它幾乎無法匹配class
和id
。
我如何使用原始的 JavaScript 來實現這一點(微信小程序不支持任何其他庫,例如 jQuery)?
這里有一些代碼可以將從后端收到的任何 html 代碼轉換為所需的格式。 無論遇到什么樣的元素和多少元素,它們都將被轉換為<text
> 元素,其.className
由它們的id
(如果可用)、它們的原始.className
和它們的原始.tagName
(小寫)組成:
const htmlArr=[`<div> <h2 id="Title">Here is an H2</h2> <article class="ContentArticle"> There are some articles. </article> </div>`, `<div> <h2 id="Title">Here is another H2</h2> <article class="ContentArticle"> And here are some more. </article> </div>`, `<div> <h3 id="Title">Here is an H3 heading</h3> <article class="ContentSubArticle"> This is a sub-article. </article> </div>`]; document.body.innerHTML=htmlArr.map(d=>{ let div=document.createElement("div"); div.innerHTML=d; return '<view class="div">'+[...div.children[0].children].map(e=>`<text class="${((e.id||"")+" "+e.className).trim()} ${e.tagName.toLowerCase()}">${e.innerHTML}</text>`).join("")+'</view>'; }).join("\n"); console.log(document.body.innerHTML)
htmlArr
是一個包含可能的 html 字符串的數組。 在上面的代碼片段中,所有字符串都被轉換,然后使用document.body.innerHTML
放到頁面上。 這只是為了演示目的。 轉換輸出當然可以以不同的方式使用
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.