Javascript 备忘

1遍历所有属性

var person={fname:"John",lname:"Doe",age:25};

for (x in person)
{
  txt=txt + person[x];
}

2.array 有 lenth 属性

var arr = new Array();
var len = arr.lenth;

3 === 类型也相同

4 访问属性的两种方法

objectName.propertyName
objectName["propertyName"]

5 支持 try catch throw

6 isNaN(x) 判断是否数字

7 当你有一个对象的多个属性或者方法需要操作时,就可以使用with

var o=document.createElement("div");
with(o){ style.cursor="pointer"; style.zIndex="100"; innerHTML="aaaa";}
document.body.appendChild(o);

等同于

var o=document.createElement("div");
o.style.cursor="pointer";
o.style.zIndex="100";
o.innerHTML="aaaa";
document.body.appendChild(o);

简化书写

8 元素下的元素

var x=document.getElementById("main");
var y=x.getElementsByTagName("p");

9 .getElementsByClassName //样式名
    getElementById
     getElementsByTagName // 标签名 如 ul li p div

10.如需改变 HTML 元素的样式,请使用这个语法:

document.getElementById(id).style.property=new style
例子:document.getElementById("p2").style.color="blue";

11. 显示和隐藏

<input type="button" value="隐藏文本" onclick="document.getElementById('p1').style.visibility='hidden'" />
<input type="button" value="显示文本" onclick="document.getElementById('p1').style.visibility='visible'" />

12. 添加节点有两种方法:
  <1> 用innerHtml注入
  <2> 用var para=document.createElement("p");然后 document.getElementById("div1").appendChild(para);


13. 移除元素
  var child=document.getElementById("p1");
  child.parentNode.removeChild(child);

14. JavaScript 提供多个内建对象,比如 String、Date、Array 等等。

15. 创建一个新对象:
  <1> person={firstname:"John",lastname:"Doe",age:50,eyecolor:"blue"};
  <2> person=new Object();person.firstname="Bill";person.lastname="Gates";

<3> 用初始函数创建
function person(firstname,lastname,age,eyecolor)
{
  this.firstname=firstname;
  this.lastname=lastname;
  this.age=age;
  this.eyecolor=eyecolor;
}

16. 成员函数:方法只不过是附加在对象上的函数。(function 内可以新建function)
  function person(firstname,lastname,age,eyecolor)
  {
    this.firstname=firstname;
    this.lastname=lastname;
    this.age=age;
    this.eyecolor=eyecolor;

    this.changeName=changeName;
    function changeName(name)
    {
      this.lastname=name;
    }
  }

17.字符串常用方法:
  indexOf() 来定位字符串中某一个指定的字符首次出现的位置。
  match() 来查找字符串中特定的字符,并且如果找到的话,则返回这个字符。
  replace() 方法在字符串中用某些字符替换另一些字符。
  length 返回字符串的长度


18. var date = new Date() 获得时间

19. 获得窗体大小
  var w=window.innerWidth|| document.documentElement.clientWidth|| document.body.clientWidth;
  var h=window.innerHeight||document.documentElement.clientHeight|| document.body.clientHeight;

20.提示窗:alert("文本")confirm("文本")prompt("文本","默认值")

21.可以用for (x in mycars) 遍历数组

22. 数组常用arr.join(".") 用.连接生成字符串,arr.concat(arr2)连接两个数组

原文地址:https://www.cnblogs.com/GhostZCH/p/3187249.html