基于dom編程中 動態(tài)創(chuàng)建與刪除元素的使用
更新時間:2013年04月17日 14:26:34 作者:
本篇文章小編將為大家介紹,基于dom編程中動態(tài)創(chuàng)建與刪除元素的使用,有需要的朋友可以參考一下
復制代碼 代碼如下:
<html>
<head>
<script type="text/javascript">
function test(){
//createElement() 創(chuàng)建一個指定標簽名的元素[比如:動態(tài)創(chuàng)建超鏈接]
var createa=document.createElement("a");
createa.id="a1";
createa.innerText="連接到百度";
createa.;
//createa.color="green" ////添加顏色(不要忘記style屬性,不然沒有效果)
createa.style.color="green"
//添加默認位置--body 并且添加子節(jié)點
//document.body.appendChild(createa);
//放置指定位置
document.getElementById("div1").appendChild(createa);
}
function test2(){
//指定位置刪除節(jié)點removeChild()
document.getElementById("div1").removeChild(document.getElementById("a1")); //id 名重復 js只取第一個
}
</script>
</head>
<body>
<!--動態(tài)創(chuàng)建元素-->
<input type="button" value="創(chuàng)建一個a標簽" onclick="test()"/><br/>
<input type="button" value="刪除創(chuàng)建一個a標簽" onclick="test2()"/>
<div id="div1" style="width:400px;height:300px;border:1px solid silver">
</div>
</body>
</html>
復制代碼 代碼如下:
<html>
<head>
<script type="text/javascript">
function test(){
//createElement() 創(chuàng)建一個指定標簽名的元素[比如:動態(tài)創(chuàng)建超鏈接]
var createa=document.createElement("a");
createa.id="a1";
createa.innerText="連接到百度";
createa.;
//createa.color="green" ////添加顏色(不要忘記style屬性,不然沒有效果)
createa.style.color="green"
//添加默認位置--body 并且添加子節(jié)點
//document.body.appendChild(createa);
//放置指定位置
$("div1").appendChild(createa);
}
function test2(){
//指定位置刪除節(jié)點removeChild()
$("div1").removeChild($("a1"));
}
//定義一個函數(shù) 返回給定id的對象
function $(id){
return document.getElementById(id);
}
</script>
</head>
<body>
<!--動態(tài)創(chuàng)建元素-->
<input type="button" value="創(chuàng)建一個a標簽" onclick="test()"/><br/>
<input type="button" value="刪除創(chuàng)建一個a標簽" onclick="test2()"/>
<div id="div1" style="width:400px;height:300px;border:1px solid silver">
</div>
</body>
</html>
相關(guān)文章
javascript學習筆記整理(概述、變量、數(shù)據(jù)類型簡介)
這篇文章主要介紹了javascript學習筆記整理(概述-變量-數(shù)據(jù)類型),需要的朋友可以參考下2015-10-10JavaScript中的setMilliseconds()方法使用詳解
這篇文章主要介紹了JavaScript中的setMilliseconds()方法使用詳解,是JS入門學習中的基礎(chǔ)知識,需要的朋友可以參考下2015-06-06javascript函數(shù)中的arguments參數(shù)
arguments當然只在function體內(nèi)才有意義, arguments.length 返回的是傳入function的實參個數(shù)2010-08-08