简体   繁体   English

如何将一个 html 元素转换为另一个元素?

[英]How can I convert one html element to another element?

Recently I have been coding the WeChat mini program.最近一直在写微信小程序。

There are some HTML strings will get from the remote server (these strings are also used by the website, so it has to convert by JavaScript) and render into the body of the mini program.有一些 HTML 字符串会从远程服务器获取(这些字符串也被网站使用,所以它必须通过 JavaScript 转换)并渲染到小程序的主体中。

Whereas, WeChat mini program cannot accept the HTML strings that I have to convert it.而微信小程序不能接受我必须转换的HTML字符串。

For example, the HTML strings are like this:例如,HTML 字符串如下所示:

<div>
   <h2 id="Title">Here is a H2</h2>
   <article class="ContentArticle">
   There are some articles.
   </article>
</div>

I have to convert them like this:我必须像这样转换它们:

<view class="div">
   <text class="Title h2">Here is a H2</text>
   <text class="ContentArticle article">
   There are some articles.
   </text>
</view>

In my first opinion, I consider achieving this by String.replace method.在我的第一个意见中,我考虑通过String.replace方法来实现这一点。 However, it can hardly match the class and id .但是,它几乎无法匹配classid

How can I achieve this by using the original JavaScript (the WeChat mini program does not support any other library such as jQuery)?我如何使用原始的 JavaScript 来实现这一点(微信小程序不支持任何其他库,例如 jQuery)?

Here is some code that will transform any html code received from your backend into the desired format.这里有一些代码可以将从后端收到的任何 html 代码转换为所需的格式。 No matter what kind of and how many elements are encountered, they will be converted into <text > elements with .className s composed of their id (if available), their original .className and their original .tagName (in lower case):无论遇到什么样的元素和多少元素,它们都将被转换为<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 is an array with possible html strings. htmlArr是一个包含可能的 html 字符串的数组。 In the snippet above all strings are converted and then put on the page by using document.body.innerHTML .在上面的代码片段中,所有字符串都被转换,然后使用document.body.innerHTML放到页面上。 This was merely done for demonstration purposes.这只是为了演示目的。 The conversion output can of course be used in different ways转换输出当然可以以不同的方式使用

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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