Javascript学习笔记

通过这篇文章不断记录js使用过程中遇到的问题解决方法。

获取iframe内页面的window对象

设有html文件0.html

1
<html><body><iframe id="f1" src="1.html"></iframe></body></html>

在0.html中获得1.html的window对象:

1
2
3
4
5
6
x=window.frames["f1"].contentWindow;
y=document.getElementById('f1').contentWindow;
z=jQuery('#f1')[0].contentWindow;
x==y==z
#获得父window对象:
x.parent;

JSON对象与字符串互转

1
2
3
4
str = '{"name":"aaa","age":33}';
//obj = eval('('+str+')');
obj1 = JSON.parse(str);
str1 = JSON.stringify(obj);

jquery选择器对象与dom对象互转

1
2
3
4
obj1 = document.getElementById('myid');
obj2 = $(obj1);
obj3 = $('#myid');
obj4 = obj3[0];

获得button所在form的id

1
2
document.getElementById('b1').form.id;
form.children;

javascript获取html DOM的父、子、相邻节点

1
2
3
4
5
6
7
8
9
10
11
document.getElementById(id);//通过节点id属性获得
document.getElementsByName(name);//通过节点name属性获得
document.getElementsByTagName(tagName);//通过节点标签名获得如div,p等
dom.parentNode//获得父节点
//获得子节点
dom.firstChild;//获得第一个子节点
dom.lastChild;//获得最后一个子节点
dom.children;//获得所有直接子节点
//获得相邻节点
dom.previousSibling;//获得前一个节点
dom.nextSibling;//获得后一个节点

js添加、删除html元素

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
//为body增加div元素
d1 = document.createElement('div');
d1.id = 'd1';
document.body.appendChild(d1);
//为d1增加p元素
p1 = document.createElement('p');
p1.id = 'p1';
t1 = document.createTextNode('段落1');
p1.appendChild(t1);
d1.appendChild(p1);
//在末尾追加p元素
p2 = document.createElement('p');
p2.id = 'p2';
t2 = document.createTextNode('段落2');
p2.appendChild(t2);
d1.appendChild(p2);
//在某个元素前增加元素
p0 = document.createElement('p');
p0.id = 'p0';
t0 = document.createTextNode('段落0');
p0.appendChild(t0);
d1.insertBefore(p0, p1);
//删除元素p1
p1.parentNode.removeChild(p1);
//增加元素<a>
a1 = document.createElement('a');
a1.href = 'javascript:alert("hello");';
a1.innerHTML = '链接1';
d1.appendChild(a1);

获得当前页的url

1
2
3
4
5
6
window.location.href;//获取url
window.location.host;//获取主机名
window.location.port;//获取端口
window.location.protocal;//获取协议
window.location.pathname;//获取路径名
window.location.search;//获取参数

不断更新中…