[轉]你不須要jQuery

徹底沒有否認jQuery的意思,jQuery是一個神奇的、很是有用的工具,能夠節省咱們大量的時間。css

可是,有些時候,咱們只須要jQuery的一個小功能,來完成一個小任務,徹底沒有必要加載整個jQuery程序庫。下面是一些用簡單JavaScript實現jQuery功能特徵的代碼彙總。固然,這個彙總並不徹底,你最好仍是看一下《你不須要jQuery(一)html

查找搜索(選擇器)

按ID查找:jquery

$('#foo')
document.getElementById('foo')

獲取Html內容:web

$(el).html();
el.innerHTML;

 

獲取屬性值:json

$(el).attr('tabindex');
el.getAttribute('tabindex');

 

按class名搜索:ide

$('.bar')
document.getElementsByClassName('bar')

 

按標記名搜索:工具

$('span')
document.getElementsByTagName('span')

 

按子元素搜索:fetch

$('#foo span')
document.getElementById('foo').getElementsByTagName('span')

 

搜索特殊元素:spa

$('html')
document.documentElement

$('head')
document.head

$('body')
document.body

 

元素屬性操做

獲取/設置HTML:code

$('#foo').html()
document.getElementById('foo').innerHTML

$('#foo').html('Hello, world!')
document.getElementById('foo').innerHTML = 'Hello, world!'

 

添加/刪除/搜索判斷class:

$('#foo').addClass('bar')
document.getElementById('foo').className += ' bar '

$('#foo').removeClass('bar')
document.getElementById('foo').className = document.getElementById('foo').className.replace(/\bbar\b/gi, '')

$('#foo').hasClass('bar')
document.getElementById('foo').className.search(/\bbar\b/gi) !== -1

 

元素值:

$('#foo').val()
document.getElementById('foo').value

 

特效

隱藏/顯示操做:

$('#foo').show()
document.getElementById('foo').style.display = ''

$('#foo').hide()
document.getElementById('foo').style.display = 'none'

 

修改CSS樣式:

$('#foo').css('background-color', 'red')
document.getElementById('foo').style.backgroundColor = 'red'

 

事件

頁面加載完成(ready)

在jQuery裏,咱們最常使用的是$(document).ready。對於它,下面是替換方法:

document.onreadystatechange = function() {
    if (document.readyState === 'complete') {
        // DOM is ready!
    }
};

 

點擊事件

$('#foo').click(function() { ... })
document.getElementById('foo').onclick = function() { ... }

 

AJAX

這個技術咱們之後有一篇文章會單獨介紹。這裏只點一下,就是用fetch()方法。

工具類技術

分析JSON:

jQuery.parseJSON(json)
JSON.parse(json)
 

總結

從上面的代碼,咱們能夠看出,jQuery裏的不少功能均可以用不少簡單的JavaScript代碼實現。jQuery雖然很好用,但它有體積的負擔,若是遇到一個問題,你能夠用簡單的代碼實現,而不用去加載jQuery,這豈不是更高效,更實用的方法嗎?

轉自:http://www.webhek.com/you-do-not-need-jquery2

相關文章
相關標籤/搜索