Dom查找方式
直接查找
var obj = document.getElementById('i1')
间接查找
文件内容操作:
innertext 仅仅查找文本内容
innerHTML 查找全部内容(文本和标签)
举例:
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <title></title> </head> <body> <div id="i1"> 丸子 <a>蘑<span>菇</span></a> </div> <input type="text" id="i2"> <select id="i3"> <option value="11">北京1</option> <option value="12">北京2</option> <option value="13">北京3</option> </select> <textarea id="i4"></textarea> </body> </html>s1
obj = document.getElementById('i1') <div id="i1">…</div> obj.innerText "丸子 蘑菇"
obj.innerHTML
"
丸子
<a>蘑<span>菇</span></a>
"
innertext可以赋值:
var obj = document.getElementById('i1') undefined obj = document.getElementById('i1') <div id="i1">猫咪</div> obj.innerText "丸子 蘑菇" obj.innerText = "猫咪" "猫咪"
如果innertext=标签的情况:
obj = document.getElementById('i1') <div id="i1">…</div> obj.innerText "丸子 蘑菇" obj.innerText ="<a href='http://www.baidu.com'>wanzi</a>" "<a href='http://www.baidu.com'>wanzi</a>"
obj.innerText
"<a href='http://www.baidu.com'>wanzi</a>"
标签被当成字符串设置成文本内容了
使用innerHTML就会把标签设置上
value
对于input标签 获取input的值,也可以修改input的值
obj = document.getElementById('i2') <input type="text" id="i2"> obj.value "" obj.value "hahahah" obj.value = "wanzi" "wanzi"
select 获取选中的value值 (selectedIndex),也可修改value的值
obj = document.getElementById("i3") <select id="i3">…</select> obj.value "11" obj.value = 12 12 obj.value = 13 13
textarea value获取当前标签中的值
obj = document.getElementById("i4") <textarea id="i4"></textarea> obj.value "" obj.value = "wanzi" "wanzi"
value的应用
搜索框的例子:
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <title></title> </head> <body> <div style="width:600px;margin:0 auto;"> <input id="i1" onfocus="Focus();" onblur="Blur();" type="text" value="请输入关键字"> <input type="text" placeholder="请输入关键字"> </div> <script> function Focus(){ var tag = document.getElementById('i1'); var val = tag.value; if (val == "请输入关键字"){ tag.value = ""; } } function Blur(){ var tag = document.getElementById('i1'); var val = tag.value; if (val.length == 0){ tag.value = "请输入关键字"; } } </script> </body> </html>
结束