[转]你不需要jQuery
2024-10-10 15:07:59
完全没有否定jQuery的意思,jQuery是一个神奇的、非常有用的工具,可以节省我们大量的时间。
但是,有些时候,我们只需要jQuery的一个小功能,来完成一个小任务,完全没有必要加载整个jQuery程序库。下面是一些用简单JavaScript实现jQuery功能特征的代码汇总。当然,这个汇总并不完全,你最好还是看一下《你不需要jQuery(一)》
查找搜索(选择器)
按ID查找:
$('#foo')
document.getElementById('foo')
获取Html内容:
$(el).html();
el.innerHTML;
获取属性值:
$(el).attr('tabindex');
el.getAttribute('tabindex');
按class名搜索:
$('.bar')
document.getElementsByClassName('bar')
按标记名搜索:
$('span')
document.getElementsByTagName('span')
按子元素搜索:
$('#foo span')
document.getElementById('foo').getElementsByTagName('span')
搜索特殊元素:
$('html')
document.documentElement $('head')
document.head $('body')
document.body
元素属性操作
获取/设置HTML:
$('#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
最新文章
- 【转】Caffe初试(八)Blob,Layer和Net以及对应配置文件的编写
- bug-android之INSTALL_FAILED_NO_MATCHING_ABIS
- 0525Scrum项目7.0
- Android图片浏览器之缩略图
- LintCode Kth Largest Element
- Notify通知
- 你真的会玩SQL吗?实用函数方汇总
- SQL Server索引怎么用
- 利用php的ob缓存机制实现页面静态化
- IE兼容HTML5
- java并发编程_基本模块构建
- Arduino 各种模块篇 光敏感应模块 light sensor
- Chapter 2 Open Book——27
- MySQL常用函数及日期
- servlet与jsp的区别(转)
- Docker 如何支持多种日志方案?- 每天5分钟玩转 Docker 容器技术(88)
- VimFaultException A specified parameter was not correct configSpec.guestId
- JavaScript原型(第五天)
- css点滴1—八种方式实现元素垂直居中
- servlet生成图片验证码
热门文章
- Maven下载依赖项的源代码(source code)和Javadoc
- Excel 点滴积累
- vux 中popup 组件 Mask 遮罩在最上层问题的解决
- html+css做的丝带标签
- Pyqt SpVoice朗读功能
- oracle 11g RAC安装节点二执行结果错误CRS-5005: IP Address: 192.168.1.24 is already in use in the network
- CozyRSS开发记录1-原型图与Grid
- mysql多表联合查询
- 【Android】achartengine的柱状图和饼状图的使用
- MyBabis 用法详解