window.onload = function()
{
var tables = [];
tables[0] = "<table><tbody><tr><td>あいうえお</td></tr></tbody></table>";
tables[1] = "<table><tbody><tr><td>かきくけこ</td></tr></tbody></table>";
tables[2] = "<table><tbody><tr><td>さしすせそ</td></tr></tbody></table>";
var index = parseInt(Math.random() * tables.length);
setHTML.call(document.body, tables[index]);
}
function setHTML(htmlText)
{
//元の子ノードを削除する。
while(this.hasChildNodes())
this.removeChild(this.firstChild);
var lastChild = this;
for(var ix = 0; ix < htmlText.length; ) {
var nextIx = ix + 1;
switch(htmlText.charAt(ix)) {
case "<":
nextIx = htmlText.indexOf(">", ix) + 1;
//属性の開始まで。
var tagEnd = htmlText.indexOf(" ", ix);
if(tagEnd < ix || tagEnd > nextIx)
tagEnd = nextIx - 1;
var tag = htmlText.substring(ix + 1, tagEnd);
//終了タグであれば最終要素を親要素に置き換える。
if(tag.charAt(0) == "/") {
lastChild = lastChild.parentNode;
break;
}
//開始タグであれば要素を追加し、最終要素にする。
var tagElement = document.createElement(tag);
lastChild.appendChild(tagElement);
lastChild = tagElement;
//属性をセットする。
var attributeText = htmlText.substring(tagEnd + 1, nextIx - 1);
setAttributes(tagElement, attributeText);
break;
default:
//テキストノードを追加する。
nextIx = htmlText.indexOf("<", ix);
if(nextIx < 0)
nextIx = htmlText.length;
var text = htmlText.substring(ix, nextIx);
lastChild.appendChild(document.createTextNode(text));
}
ix = nextIx;
}
//属性セット関数
function setAttributes(targetElement, attributeText)
{
for(var ix = 0; ix < attributeText.length; ) {
//属性名称取得
var nextIx = attributeText.indexOf("=", ix);
var name = attributeText.substring(ix, nextIx);
//属性内容取得
ix = nextIx + 1;
nextIx = attributeText.indexOf(" ", ix);
if(nextIx < 0)
nextIx = attributeText.length;
var value = attributeText.substring(ix + 1, nextIx - 1);
//属性の追加
if(name.substring(0, 2) == "on")
addEvent.call(targetElement, name.substring(2), new Function("event", value));
else
targetElement.setAttribute(name, value);
ix = nextIx + 1;
}
//対象にイベントを追加する。
function addEvent(eventName, eventFunction)
{
if(this.addEventListener)
this.addEventListener(eventName, thatEvent, false);
else if(this.attachEvent)
this.attachEvent("on" + eventName, ieEvent);
//IE用イベント
function ieEvent() {
if(typeof eventFunction == "function")
return eventFunction.call(window.event.srcElement, window.event);
}
//その他用イベント
function thatEvent(e) {
if(typeof eventFunction == "function")
return eventFunction.call(e.target, e);
}
}
}
}