convert html to javascript

半腔热情 提交于 2019-11-29 13:49:49

问题


Does anybody know if there is a tool around that can convert html to javascript.

For example:

<div>
</div>

would convert to

aDiv = document.createElement('div');
document.appendChild(aDiv);

etc

I'm am doing a few html templates for UI components and am using MooShell for prototyping. It would be great to be able to auto-generate the javascript that will build the component's html.

Thanks


回答1:


I'd suggest taking a look at John Resig's pure javascript HTML parser. It consists of a SAX style parser for HTML and includes an XML serializer, a DOM builder and a DOM creator. Each takes a string of HTML as input.

In particular, the HTMLtoDOM method could easily be repurposed to return the string of javascript required to build the DOM for any input string of HTML.




回答2:


If there was no such tool (which I highly think is the case), I would solve this problem the same old good way: build my own parser.




回答3:


I see other people have given you plenty of tips on how to do this, but my two cents on one thing to bear in mind.

If you are inserting/removing/modifying elements to/from the DOM using client-side Javascript, you will notice that with a framework such as jQuery, you will be unable to call and manipulate the DOM elements you have added in on the fly.

The best way round this is to look up using the jQuery Live plugin.




回答4:


The PrototypeJS Framework has an insert() method which is able to parse html code, so you can do something like:

$$('body')[0].insert(stringWithYourHTMLCode);

Or you define a container for your content:

$('containerId').insert(stringWithYourHTMLCode);



回答5:


I'm not sure about your situation, but if you have components in HTML they should have events, IDs and binding... So I don't think there is a human-like genius script that can generate this code. Add to that, your problem is very specific. It may be somewhere in some IT corporation, but it's not something that web developers uses daily like jQuery.



来源:https://stackoverflow.com/questions/3520255/convert-html-to-javascript

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!