1. select 和options
<html>
<select name="first" size="1" id="first" style="width:100px">
<option value="">option>
<option value="1">电源option>
<option value="2">主网(电网基建)option>
<option value="3">城网option>
<option value="4">农网option>
<option value="5">小型基建option>
<option value="6">电网技改option>
<option value="7">其他资本性支出option>
select>
html>
<script>...
function initFirst() ...{
var first = document.getElementById('first');
for (var i = 0; i < first.options.length; i++) ...{
if (first.options[i].value == <%=type%>) ...{
first.options[i].selected = true;
}
}
}
initFirst();
script>
2.js验证输入是否为数字
var str = "ds";
var num = "123";
isNaN(str)返回true
isNaN(num)返回false
3.截获窗口关闭事件
onunload,不一定只有关闭时响应,只要离开页面(比如刷新之前、url改变)就会响应。另外,在关闭之前还会响应一个onbeforeunload事件。
<HTML>
<BODY onunload="alert('close!');" onbeforeunload="alert('onbeforeunload')">
BODY>
HTML>
4.(转自:http://topic.csdn.net/t/20010529/08/138407.html)
event对象指当前触发的事件对象, window.event.srcElement是指触发事件的对象。比如你设定document.onclick = myfunc;这时所有页面点击的事件都交给myfunc处理,在myfunc函数里可以写vSrc = window.event.srcElement,知道用户是点击了什么地方,做相应处理。
<script languange = "javascript">
document.onclick = myfunc;
function myfunc()
...{
alert(window.event.srcElement.nodeName);
}
script>
5.with
function createTable() ...{
var doc = document;
var oTable = doc.createElement("table");
with(oTable) ...{
border = "1";
width = "100%";
var oTbody = doc.createElement("tbody");
with(oTbody) ...{
var oTr1 = doc.createElement("tr");
with(oTr1) ...{
var oTd1 = doc.createElement("td");
var oText1 = doc.createTextNode("cell 1,1");
oTd1.appendChild(oText1);
var oTd2 = doc.createElement("td");
var oText2 = doc.createTextNode("cell 1,2");
oTd2.appendChild(oText2);
appendChild(oTd1);
appendChild(oTd2);
}
appendChild(oTr1);
}
appendChild(oTbody);
}
doc.body.appendChild(oTable);
}
6. 获得html对象
根据id获得标签的对象可以不使用
var someId = "textbox1";
var o = document.getElementById(someId);
alert(o.value);
可以直接使用
alert(textbox1.value);
7.数组
var aCity=...{"a":...{"flag":"aa", "value":"bb"},11:"北京",12:"天津",13:"河北",14:"山西",15:"内蒙古",21:"辽宁",22:"吉林",23:"黑龙江 ",31:"上海",32:"江苏",33:"浙江",34:"安徽",35:"福建",36:"江西",37:"山东",41:"河南",42:"湖北 ",43:"湖南",44:"广东",45:"广西",46:"海南",50:"重庆",51:"四川",52:"贵州",53:"云南",54:"西藏 ",61:"陕西",62:"甘肃",63:"青海",64:"宁夏",65:"新疆",71:"台湾",81:"香港",82:"澳门",91:"国外 "};
for (var i in aCity) ...{
alert(i + ": " + aCity[i]);
}
alert(aCity["a"]["flag"]); // 等价于 alert(aCity.a.flag); 但如果要访问数组中北京这个元素的话则不能使用aCity.11
// 下面是个Array
var arr = ["a", "b", "c"]; // 等价于 var arr = new Array("a", "b", "c");
alert(arr[1]);
我经常犯一个错误,就是访问数组或者是访问Array对象时会用aCity(11),这是我对js的理解有问题,小括号"()"是用来访问方法的