1. 程式人生 > >關於JS的DOM操作——重要實例的操作

關於JS的DOM操作——重要實例的操作

i++ dom width lds 內容 click value mar cli

1.復選框與按鈕的配合使用的DOM操作

<body>

<input type="checkbox" id="ckb1" /><br><br>
<input type="button" value="下一步" id="btn1" disabled="disabled" />

</body>

<script>

document.getElementById(‘ckb1‘).onclick = function(){


var ckb1 = document.getElementById(‘ckb1‘);
var btn1 = document.getElementById(‘btn1‘);

if(ckb1.checked){
btn1.removeAttribute(‘disabled‘);
}
else{
btn1.setAttribute(‘disabled‘,‘‘);
}
}
</script>

2.下拉列表、文本框與按鈕配合使用的DOM操作(兩種方法)

<body>

<select id="skd" size="7" style="width: 100px;"></select><br>
<select id="slt" size="7" style="width: 100px;"></select><br>
<input type="text" id="ipt2" /><br>
<input type="text" id="txt" /><br>


<input type="button" id="btn2" value="添加"/>
</body>
<script>
//第一種方法(拼字符串)

// document.getElementById(‘btn2‘).onclick = function(){
// var ipt2= document.getElementById(‘txt‘).value;
// var skd = document.getElementById(‘skd‘);
// skd.innerHTML += "<option>"+ ipt2 +"</option>";
// document.getElementById(‘ipt2‘).value="";
// }

//第二種方法(造元素)

var txt = document.getElementById(‘txt‘);
var slt = document.getElementById(‘slt‘);

document.getElementById(‘btn2‘).onclick = function(){
// 新建一個option對象
var opt = document.createElement(‘option‘);
// 設置option對象的值(指向賦值)
opt.value = txt.value;
// 設置option對象的內容
opt.innerHTML = txt.value;
// 添加到slt(名)的對象
slt.appendChild(opt);
}

</script>

3.下拉列表與按鈕的雙向交換效果

<body>

<select id="oldSelect" size="10" multiple="multiple" style="width: 100px;float: left;position: relative">
<option >北京</option>
<option >上海</option>
<option >上海</option>
<option >深圳</option>
<option >香港</option>
</select>
<select id="newSelect" size="10" multiple="multiple" style="width: 100px;float: left;margin-left: 20px;position: relative;">
<option >籃球</option>
<option >遊泳</option>
<option >擊劍</option>
<option >排球</option>
<option >舉重</option>
</select>

<br><br><br><br><br><br><br><br><br><br>

<input type="button" id="btn1" value="添加到右" style="float: left;"/>
<input type="button" id="btn2" value="添加到左" style="float: left;margin-left: 50px;"/>

<script>

document.getElementById(‘btn1‘).onclick=function(){

var oldSelect = document.getElementById(‘oldSelect‘);

for(var i=0;i<oldSelect.options.length;i++){
if(oldSelect.options[i].selected){
var newSelect = document.getElementById(‘newSelect‘);
newSelect.appendChild(oldSelect.options[i]);
}
}
alert(oldSelect.options[oldSelect.options.length].value);
}

document.getElementById(‘btn2‘).onclick=function(){

var newSelect = document.getElementById(‘newSelect‘);

for(var i=0;i<newSelect.options.length;i++){
if(newSelect.options[i].selected){
var oldSelect = document.getElementById(‘oldSelect‘);
oldSelect.appendChild(newSelect.options[i]);
}
}
alert(newSelect.options[newSelect.options.length].value);
}

</script>

關於JS的DOM操作——重要實例的操作