将手工HTML代码转化为DOM代码

最近在学习DOM高级程序设计,跟着书上的的例子写了个代码转化工具,下面附上源码,目前使用的第三方js库(也是书上的例子)是ADS.js。

index.html

<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8"/>
<link href="index.css" rel="stylesheet" type="text/css" />
<script type="text/javascript" src="ADS.js"></script>
</head>

<body>
<p>If you click on me, I will disappear.</p>
<a href="#" id="firefox"></a>

<div id="content">
<form id="generator" action="">
	<fieldset>
		<h2>Source</h2>
		<label for="source">Enter an HTML document fragment</label>
		<textarea id="source" cols="30" rows="15"></textarea>
		<input id="generate" type="button" value="↓ generate ↓" />
		<h2>DOM Code</h2>
		<label for="result">and volia! DOM goodness:</label>
		<textarea id="result" cols="30" rows="15"></textarea>
	</fieldset>
</form>
</div>


</body>
</html> 
<script type="text/javascript" src="myLogger.js"></script>
<script type="text/javascript" src="generateDOM.js"></script>
<script type="text/javascript" src="test.js"></script>
generateDOM.js
(function(){
	function encode(str){
		if(!str) return null;
		str = str.replace(/\\/g, '\\\\');
		str = str.replace(/';/g, "\\'");
		str = str.replace(/\s+^/mg, "\n");
		return str;
	}

	function checkForVariable(v){
		if(v.indexOf('$') == -1){
			v = '\'' + v + '\'';
		}else{
			v = v.substring(v.indexOf('$')+1);
			requirVariables += 'var' + v + ';\n';
		}
		return v;
	}

	var domCode = '';
	var nodeNameCounters = [];
	var requirVariables = '';
	var newVariables = '';

	function generate(strHTML, strRoot){
		var domRoot = document.createElement('DIV');
		domRoot.innerHTML = strHTML;

		domCode = '';
		nodeNameCounters = [];
		requirVariables = '';
		newVariables = '';

		var node = domRoot.firstChild;

		while(node){
			ADS.walkTheDOMRecursive(processNode, node, 0, strRoot);
			node = node.nextSibling;
		}

		domCode = '/* requirVariables in this code\n' + requirVariables + '*/\n\n' + domCode + '\n\n' + '/* new object in this code\n' + newVariables + '*/\n\n';
		return domCode; 

	}

	function processAttribute(tabCount, refParent){

		if(this.nodeType != ADS.node.ATTRIBUTE_NODE) return;

		var attrValue = (this.nodeValue ? encode(this.nodeValue.trim()) : '');

		if(this.nodeName == 'cssText') alert('true');

		if(!attrValue) return;

		var tabs = (tabCount ? '\t'.repeat(parseInt(tabCount)) : '');

		switch(this.nodeName){
			default:
				if(this.nodeName.substring(0,2) == 'on'){
					domCode += tabs + refParent + '.' + this.nodeName + ' = function(){' + attrValue + '}\n';
				}else{
					domCode += tabs + refParent +'.setAttribute(\'' + this.nodeName+'\',' + checkForVariable(attrValue) +');\n';
				}
				break;
			case 'class':
				domCode += tabs + refParent + '.className = ' + checkForVariable(attrValue) + ';\n';
				break;
			case 'style':
				var style = attrValue.split(/\s*;\s*/);

				if(style){
					for(pair in style){
						if(!style[pair]) continue;

						var prop = style[pair].split(/\s*:\s*/);
						if(!prop[1]) continue;

						prop[0] = ADS.camelize(prop[0]);
						
						var propValue = checkForVariable(prop[1]);

						if(prop[0] == 'float'){
							domCode += tabs + refParent + '.style.cssFloat = ' + propValue + ';\n';
							domCode += tabs + refParent + '.stryle.styleFloat = ' + propValue + ';\n';
						}else{
							domCode += tabs + refParent + '.style.' + prop[0] + ' = ' + propValue + ';\n';
						}
					}
				}
				break;
		} 
		
	}

	function processNode(tabCount, refParent){

		var tabs = (tabCount ? '\t'.repeat(parseInt(tabCount)) : '');

		switch(this.nodeType){
			case ADS.node.ELEMENT_NODE:
				if(nodeNameCounters[this.nodeName]){
					++nodeNameCounters[this.nodeName];
				}else{
					nodeNameCounters[this.nodeName] = 1;
				}

				var ref = this.nodeName.toLowerCase()+nodeNameCounters[this.nodeName];

				domCode += tabs + 'var' + ref + ' = document.createElement(\'' + this.nodeName + '\');\n';

				newVariables += '' + ref + ';\n';

				if(this.attributes){
					for(var i = 0; i < this.attributes.length; i++){
						ADS.walkTheDOMRecursive(processAttribute, this.attributes[i], tabCount, ref);
					}

				}
				break;

			case ADS.node.TEXT_NODE:
				var value = (this.nodeValue ? encode(this.nodeValue.trim()) : '');

				if(value){
					if(nodeNameCounters['txt']){
						++nodeNameCounters['txt'];
					}else{
						nodeNameCounters['txt'] = 1;
					}
					var ref = 'txt' + nodeNameCounters['txt'];

					value = checkForVariable(value);

					domCode += tabs + 'var' + ref + ' = document.createElement(\'' + value + '\');\n';
					newVariables += '' + ref + ';\n';
				}else{
					return;
				}

				break;

			default:
				break;
		}

		if(refParent){
			domCode += tabs + refParent + '.appendChild(' + ref + ');\n';
		}

		return ref;
	}

	window['generateDOM'] = generate;
})();

ADS.addEvent(window, 'load', function(){
	
	ADS.addEvent('generate', 'click', function(W3CEvent){

		var source = ADS.$('source').value;
		ADS.$('result').value = generateDOM(source);
	});
});


还有就是别忘了引入ADS.js  这个库在我的其他博文中可以找到。剩下的两个js是我测试其他功能的, 跟这个没关系。


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值