常用原生js與jQuery對比總結

常用原生js與jQuery對比總結

在前端開發中,我們經常會使用jQuery,因爲jQuery簡化了JavaScript編程,可以使我們的代碼更加的簡潔。
而jQuery是一個 JavaScript 庫,瞭解JavaScript 可以幫助我們更好地瞭解jQuery和編寫高性能的代碼,所以瞭解並會使用這兩者是有必要的。

一、DOM查詢——選擇器的使用

1、獲取頁面所有div**
/* jQuery */
$("div")

/* js */
document.getElementsByTagName("div")

2、根據名稱獲取頁面DOM
/* jQuery */
$("div[name='值']")

/* js */
document.getElementsByName(name)

3、根據Id獲取DOM節點
/* jQuery */
$("#idName")

/* js */
document.getElementById("idName")
document.querySelectorAll("idName")

4、根據類名獲取DOM節點
/* jQuery */
$(".className")

/* js */
document.querySelectorAll(".className")
document.getElementsByClassName(className)

5、根據選擇器返回第一個匹配的節點(selectors爲CSS選擇器)
/* jQuery */
$("selectors:first")

/* js */
document.querySelector("selectors")

二、操作class

1、爲DOM元素添加類
// jQuery
$(selector).addClass(className);

// js
el.classList.add(className);

2、刪除類
// jQuery
$el.removeClass(className);

// js
el.classList.remove(className);

3、判斷是否有該類
 /* jQuery */ 
if($(el).hasClass(classNames)) 

/* js */ 
if(el.classList.contains(classNames)) 

三、DOM更改

1、尾部追加DOM元素
// jQuery
$(parent).append($(child));
//js
parent.appendChild(child)

2、頭部追加DOM元素
// jQuery
$(parent).prepend($(child));
//js
parent.insertBefore(child, parent.childNodes[0])

3、刪除DOM元素
// jQuery
$(child).remove();
//js
child.parentNode.removeChild(child)

四、添加樣式或屬性

1、添加css
// jQuery
$el.css("propertyname","value");  //設置單個屬性值
$el.css({"propertyname":"value","propertyname":"value",...});  //設置多個屬性值

//js
el.style.propertyname="propertyValue";

2、獲取css值
// jQuery
$el.css("propertyname");  //獲取屬性值

//js
el.style.propertyname="propertyValue"; /*這個方法只能JS只能獲取寫在html標籤中的寫在style屬性中的值(style=”…”),而無法獲取定義在<style type="text/css">裏面的屬性*/

3、添加樣式
// jQuery
$el.css("propertyname","value");  //設置單個屬性值
$el.css({"propertyname":"value","propertyname":"value",...});  //設置多個屬性值
//js
el.style.propertyname="propertyValue";

4、添加屬性
// jQuery
$(selector).attr(attribute,value);  //設置單個屬性值
$(selector).attr({attribute:value, attribute:value ...});  //設置多個屬性值
$(selector).attr(attribute,function(index,oldvalue));//function爲返回屬性值的函數,該函數可接收並使用選擇器的 index 值和當前屬性值,返回的屬性值爲當前函數的新屬性值
//js
el.setAttribute(attributename,attributevalue);

5、獲取節點屬性
// jQuery
$(selector).attr(attribute);  //獲取節點屬性值
//js
el.getAttribute(attributename); //獲取節點屬性值

6、移除節點屬性
// jQuery
$(selector).removeAttr(attribute); 
//js
element.removeAttribute(attributename); 

五、Event事件

1、事件綁定
// jQuery
$(selector).on(eventName, eventHandler);
//js
el.addEventListener(eventName, eventHandler);

2、解綁事件
// jQuery
$(selector).on(eventName, eventHandler);
//js
el.removeEventListener(eventName, eventHandler);

六、顯示與隱藏

顯示與隱藏
// jQuery
$(el).show();
$(el).hide();

//js
el.style.display = '';
el.style.display = 'none';

七、頁面加載初始化

顯示與隱藏
// jQuery
//方法一
$(function(){
 // 初始化內容 
})
//方法二
$(document).ready(function(){
 // 初始化內容 
})

//js
window.onload=function(){ 
    // 初始化內容 
}
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章