彻底没有否认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'
在jQuery里,咱们最常使用的是$(document).ready
。对于它,下面是替换方法:
document.onreadystatechange = function() { if (document.readyState === 'complete') { // DOM is ready! } };
$('#foo').click(function() { ... }) document.getElementById('foo').onclick = function() { ... }
这个技术咱们之后有一篇文章会单独介绍。这里只点一下,就是用fetch()
方法。
分析JSON:
jQuery.parseJSON(json)
JSON.parse(json)
从上面的代码,咱们能够看出,jQuery里的不少功能均可以用不少简单的JavaScript代码实现。jQuery虽然很好用,但它有体积的负担,若是遇到一个问题,你能够用简单的代码实现,而不用去加载jQuery,这岂不是更高效,更实用的方法吗?