JavaScript第11回目ゼミ解答資料(加藤)
・DOMを利用してページを作成してください。
表示するものすべてをDOMを使って作成すること。
表示させるものは、何でもいいです。ただし…
・何かしらの文字列
・ボタン
・何かしらのイベント処理
・画像の表示
・ノードの削除
を含めてください。
その他は、ご自由に
IE以外(Firefoxしか試してないけど...)で動かすと妙な動作をします...w
---------------------------------------------------------------------------------
<html>
<head><title>DOMの練習</title>
<script type="text/javascript">
<!--
var i=false;
function addListener(obj, event, func, useCapture) {
if (window.addEventListener) {
obj.addEventListener(event, func, useCapture);
} else if (window.attachEvent) {
obj.attachEvent("on" + event, func);
}
}
function init(){
var bnode = document.getElementById("bid");
var txt1 = document.createTextNode("このページのものは、すべてDOMで作成しました。");
var h1 = document.createElement("h1");
h1.appendChild(txt1);
bnode.appendChild(h1);
var h5 = document.createElement("h5");
var txt2 = document.createTextNode("このボタンを押すと?");
h5.appendChild(txt2);
bnode.appendChild(h5);
var b1 = document.createElement("input");
b1.setAttribute("type", "button");
b1.setAttribute("value", "押してw");
addListener(b1, "click", change, false);
bnode.appendChild(b1);
}
function change(){
var img = document.createElement("img");
img.setAttribute("src", "images/img0.jpg");
img.setAttribute("width", "220");
img.setAttribute("height", "150");
if (window.addEventListener) {
document.getElementById("bid").childNodes[3].appendChild(img);
document.getElementById("bid").childNodes[3].setAttribute("value", "");
i = true;
} else if (window.attachEvent) {
document.getElementById("bid").childNodes[2].setAttribute("value", "犬が増殖するよ〜w");
document.getElementById("bid").appendChild(img);
}
if(i == false){
var b2 = document.createElement("input");
b2.setAttribute("id", "b2");
b2.setAttribute("type", "button");
b2.setAttribute("value", "犬うざい...");
addListener(b2, "click", del, false);
document.getElementById("bid").appendChild(b2);
i = !i;
}
}
function del(){
var nodes = document.getElementsByTagName("img");
var delmax = nodes.length;
for(var j=0; j<delmax; j++){
document.getElementById("bid").removeChild(nodes[0]);
}
document.getElementById("bid").removeChild(document.getElementById("b2"));
document.getElementById("bid").childNodes[2].setAttribute("value", "もっかい押す??");
i = !i;
}
addListener(window, "load", init, false);
//-->
</script>
</head>
<body id="bid">
</body>
</html>