js使用總結
1.周期性執行函數
setTimeout() 方法用於在指定的毫秒數後調用函數或計算運算式。
舉例:
<script type="text/javascript">var c=0;var t;function timedCount(){document.getElementById('txt').value=c;c=c+1;t=setTimeout("timedCount()",1000);}</script>或者:<script type="text/javascript">function timedCount(c){document.getElementById('txt').value=c;c=c+1;var x=function(){timedCount(c);}setTimeout(x,1000);}</script>
2.js中如何判斷對象是否存在
typeof函數:
typeof 可以用來檢測給定變數的資料類型,可能的返回值:
1. 'undefined' --- 這個值未定義;
2. 'boolean' --- 這個值是布爾值;
3. 'string' --- 這個值是字串;
4. 'number' --- 這個值是數值;
5. 'object' --- 這個值是對象或null;
6. 'function' --- 這個值是函數。
舉例:
if(typeof(key)!="undefined"&&key != ''){ //do something}
3.js中替換空格
使用a.replace(/\s+/g,'');舉例:
<script type="text/javascript">var a = ' 11 222 33 44 55 ';a = a.replace(/\s+/g,'');alert(a);</script>
4.字串分割函數
split() :把一個字串分割成字串數組。
stringObject.split(separator,howmany)
舉例:
<script type="text/javascript">var data = "1,2,3,4";var arr = data.split(",");alert(arr[0]);</script>
5.刪除數組中的元素
splice():刪除數組中的元素
arrayObject.splice(index,howmany,item1,.....,itemX)
index:必需。整數,規定添加/刪除項目的位置,使用負數可從數組結尾處規定位置。
howmany: 必需。要刪除的項目數量。如果設定為 0,則不會刪除項目。
item1, ..., itemX: 可選。向數組添加的新項目。
說明:
splice() 方法可刪除從 index 處開始的零個或多個元素,並且用參數列表中聲明的一個或多個值來替換那些被刪除的元素。如果從 arrayObject 中刪除了元素,則返回的是含有被刪除的元素的數組。
6.JSON轉換為字串
str = JSON.stringify(data); //data是json類型的資料
7.尋找子字串個數
//在data中尋找song_id的個數
var reg=new RegExp('song_id',"gi");
count = str.match(reg).length;
8.監聽輸入框變化
function immediately(){var element = document.getElementById("title");if("\v"=="v") {element.onpropertychange = webChange;}else{element.addEventListener("input",webChange,false);}function webChange(){if(element.value){//do something with element.value};}}immediately();參考:http://www.jb51.net/article/27684.htm
9.刪除div下所有子節點
function removeAllChild(){ var div = document.getElementById("songLink"); while(div.hasChildNodes()){ //當div下還存在子節點時 迴圈繼續 div.removeChild(div.firstChild); }}10.
jquery修改操作css屬性
在jquery中使用css()方法便可以css屬性實現動態修改,下面介紹常用方法:
1.擷取css屬性:$(selector).css(name)
取得第一個段落的 color 樣式屬性的值:$("p").css("color");
2.設定css屬性:$(selector).css(name,value)
將所有段落的顏色設為紅色:$("p").css("color","red");
3.使用函數來設定CSS屬性:$(selector).css(name,function(index,value))
此函數返回要設定的屬性值。接受兩個參數,index 為元素在對象集合中的索引位置(可選),value 是原先的屬性值(可選)。
將所有段落的顏色設為紅色:
$("button").click(function(){
$("p").css("color",function(){return "red";});
});
4.設定多個CSS屬性/值對:$(selector).css({property:value, property:value, ...})
$("p").css({
"color":"white",
"background-color":"#98bf21",
"font-family":"Arial",
"font-size":"20px",
"padding":"5px"
});
註:
jquery可以使用attr()函數設定屬性值,用法同css()方法
詳情參考Jquery屬性操作
本文為Eliot原創,轉載請註明出處:http://blog.csdn.net/xyw_blog/article/details/40432313