简体   繁体   English

如何用我们自己的标签替换html标签

[英]How to replace html tags with our own tags

In my MVC web application, I have a text area inside View, in that user will put HTML text so in that text, I want to replace html tags with my own custom tags. 在我的MVC Web应用程序中,我在View内有一个文本区域,该用户将HTML文本放置在该文本中,因此我想用自己的自定义标签替换html标签。

For Example: 例如:

HTML tag: HTML标记:

 <input type='text' name='MyList.First_Name' data-val='true' data-val-required='Please enter first name' /> 

Replace with: 用。。。来代替:

 [~TextFieldTag|MyList.First_Name|||0|data-val=>true|data-val-required=>Please enter first name|~] 

Can anyone suggest what is the best approach to do this? 谁能建议这样做的最佳方法是什么?

I was going to recommend a simple string replacement at first, but given the seemingly complicated nature of your replacements, that might not be the best approach. 我最初建议使用简单的字符串替换,但是鉴于替换的性质看似复杂,这可能不是最佳方法。

Probably the best approach would be to take the HTML, convert it to DOM elements, which can be done simply by throwing it into an elements innerHTML : 最好的方法可能是获取HTML,将其转换为DOM元素,只需将其放入元素innerHTML

 document.querySelector('button').addEventListener('click', () => { document.querySelector('#renderSpace').innerHTML = document.querySelector('textarea').value; }); 
 Add some HTML: <textarea></textarea> <button>Press Me</button> <div id="renderSpace"></div> 

You can position the area you render it inside of off-screen so users don't actually see it. 您可以将渲染区域放置在屏幕外,这样用户就不会实际看到它。

From there, I would walk the DOM tree (basically, start at the root, then look at all of its children, then their children, etc., recursively), reading off any properties that you deem appropriate and then writing your string replacement as you go along. 从那里,我将遍历DOM树(基本上,从根开始,然后递归地查看其所有子项,然后是其子项,等等),读取您认为合适的任何属性,然后将字符串替换写为你去吧。

That does require that they have entered valid HTML (which is generally a requirement, but can be difficult to rely on users to enter), so you'll want to have some good, user-friendly, error handling in there. 这确实需要他们输入有效的HTML(通常这是一个要求,但可能很难依靠用户输入),因此您将需要在其中提供一些良好的,用户友好的错误处理。

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

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