jquery属性的相关js实现方法
有些公司手机网站开发不用第三方的jquery或者zeptio,直接用原生的javascript。原生javascript功能是蛮强大的,只不过部分属性不支持IE8以下浏览器。下面对jquery相关方法,如何用js来实现,做一些简单总结。
元素操作
Add Class
//JQUERY
$(el).addClass(className);//js//谷歌浏览器,火狐浏览器,IE8+if(el.classList)
el.classList.add(className);else
el.className +=' '+ className;//谷歌浏览器,火狐浏览器,IE10+
el.classList.add(className);
After
//JQUERY
$(el).after(htmlString);//js 谷歌浏览器,火狐浏览器,IE8+
el.insertAdjacentHTML('afterend', htmlString);
Append
//JQUERY
$(parent).append(el);//js谷歌浏览器,火狐浏览器,IE8+
parent.appendChild(el);
Before
//JQUERY
$(el).before(htmlString);//js谷歌浏览器,火狐浏览器,IE8+
el.insertAdjacentHTML('beforebegin', htmlString);
Children
//JQUERY
$(el).children();//js//谷歌浏览器,火狐浏览器,IE8+var children =[];for(var i = el.children.length; i--;){// Skip comment nodes on IE8if(el.children[i].nodeType !=8)
children.unshift(el.children[i]);}//谷歌浏览器,火狐浏览器,IE9+
el.children
Clone
//JQUERY
$(el).clone();//谷歌浏览器,火狐浏览器,IE8+
el.cloneNode(true);
Contains
//JQUERY
$.contains(el, child);//谷歌浏览器,火狐浏览器,IE8+
el !== child && el.contains(child);
Contains Selector
//JQUERY
$(el).find(selector).length;//谷歌浏览器,火狐浏览器,IE8+
el.querySelector(selector)!==null
Each
//JQUERY
$(selector).each(function(i, el){});//js谷歌浏览器,火狐浏览器,IE8+function forEachElement(selector, fn){var elements = document.querySelectorAll(selector);for(var i =0; i < elements.length; i++)
fn(elements[i], i);}
forEachElement(selector,function(el, i){});//js谷歌浏览器,火狐浏览器,IE9+var elements = document.querySelectorAll(selector);Array.prototype.forEach.call(elements,function(el, i){});
Empty
//JQUERY
$(el).empty();//js谷歌浏览器,火狐浏览器,IE8+while(el.firstChild)
el.removeChild(el.firstChild);//js谷歌浏览器,火狐浏览器,IE9+
el.innerHTML ='';
过滤filter
//JQUERY
$(selector).filter(filterFn);//谷歌浏览器,火狐浏览器,IE8+function filter(selector, filterFn){var elements = document.querySelectorAll(selector);varout=[];for(var i = elements.length; i--;){if(filterFn(elements[i]))out.unshift(elements[i]);}returnout;}
filter(selector, filterFn);//谷歌浏览器,火狐浏览器,IE9+Array.prototype.filter.call(document.querySelectorAll(selector), filterFn);
查找子元素
//JQUERY
$(el).find(selector);//谷歌浏览器,火狐浏览器,IE8+
el.querySelectorAll(selector);
查找、选择器
//JQUERY
$('.my #awesome selector');//谷歌浏览器,火狐浏览器,IE8+
document.querySelectorAll('.my #awesome selector');
获取属性值attr
//JQUERY
$(el).attr('tabindex');//谷歌浏览器,火狐浏览器,IE8+
el.getAttribute('tabindex');
获取Html内容
//JQUERY
$(el).html();//js
el.innerHTML
获取CSS样式
//JQUERY
$(el).css(ruleName);//谷歌浏览器,火狐浏览器,IE9+
getComputedStyle(el)[ruleName];
获取文本内容
//JQUERY
$(el).text();//谷歌浏览器,火狐浏览器,IE8+
el.textContent || el.innerText
//谷歌浏览器,火狐浏览器,IE9+
el.textContent
Has Class
//JQUERY
$(el).hasClass(className);//谷歌浏览器,火狐浏览器,IE8+if(el.classList)
el.classList.contains(className);elsenewRegExp('(^| )'+ className +'( |$)','gi').test(el.className);//谷歌浏览器,火狐浏览器,IE10+
el.classList.contains(className);
元素比较
JQUERY
$(el).is($(otherEl));//js
el === otherEl
比较类名
//JQUERY
$(el).is('.my-class');//谷歌浏览器,火狐浏览器,IE8+var matches =function(el, selector){var _matches =(el.matches || el.matchesSelector || el.msMatchesSelector || el.mozMatchesSelector || el.webkitMatchesSelector || el.oMatchesSelector);if(_matches){return _matches.call(el, selector);}else{var nodes = el.parentNode.querySelectorAll(selector);for(var i = nodes.length; i--;){if(nodes[i]=== el)returntrue;}returnfalse;}};
matches(el,'.my-class');//谷歌浏览器,火狐浏览器,IE9+var matches =function(el, selector){return(el.matches || el.matchesSelector || el.msMatchesSelector || el.mozMatchesSelector || el.webkitMatchesSelector || el.oMatchesSelector).call(el, selector);};
matches(el,'.my-class');
Next
//JQUERY
$(el).next();//谷歌浏览器,火狐浏览器,IE8+// nextSibling can include text nodesfunction nextElementSibling(el){do{ el = el.nextSibling;}while( el && el.nodeType !==1);return el;}
el.nextElementSibling || nextElementSibling(el);//谷歌浏览器,火狐浏览器,IE9+
el.nextElementSibling
Offset
//JQUERY
$(el).offset();//js谷歌浏览器,火狐浏览器,IE8+var rect = el.getBoundingClientRect(){
top: rect.top + document.body.scrollTop,
left: rect.left + document.body.scrollLeft
}
Outer Width
//JQUERY
$(el).outerWidth();//js
el.offsetWidth
Parent
//JQUERY
$(el).parent();//js
el.parentNode
Position
//JQUERY
$(el).position();//js{left: el.offsetLeft, top: el.offsetTop}
Prev
//JQUERY
$(el).prev();//谷歌浏览器,火狐浏览器,IE8+// prevSibling can include text nodesfunction previousElementSibling(el){do{ el = el.previousSibling;}while( el && el.nodeType !==1);return el;}
el.previousElementSibling || previousElementSibling(el);//谷歌浏览器,火狐浏览器,IE9+
el.previousElementSibling
Remove
//JQUERY
$(el).remove();//js谷歌浏览器,火狐浏览器,IE8+
el.parentNode.removeChild(el);
Remove Class
//JQUERY
$(el).removeClass(className);//js谷歌浏览器,火狐浏览器,IE8+if(el.classList)
el.classList.remove(className);else
el.className = el.className.replace(newRegExp('(^|\\b)'+ className.split(' ').join('|')+'(\\b|$)','gi'),' ');//谷歌浏览器,火狐浏览器,IE10+
el.classList.remove(className);
Replace From Html
//JQUERY
$(el).replaceWith(string);//谷歌浏览器,火狐浏览器,IE8+
el.outerHTML =string;
Set Attributes
//JQUERY
$(el).attr('tabindex',3);//谷歌浏览器,火狐浏览器,IE8+
el.setAttribute('tabindex',3);
Set Html
//JQUERY
$(el).html(string);//谷歌浏览器,火狐浏览器,IE8+
el.innerHTML =string;
Set Style
//JQUERY
$(el).css('border-width','20px');//谷歌浏览器,火狐浏览器,IE8+// Use a class if possible
el.style.borderWidth ='20px';
Set Text
//JQUERY
$(el).text(string);//谷歌浏览器,火狐浏览器,IE8+if(el.textContent !==undefined)
el.textContent =string;else
el.innerText =string;//谷歌浏览器,火狐浏览器,IE9+
el.textContent =string;
Siblings
//JQUERY
$(el).siblings();//谷歌浏览器,火狐浏览器,IE8+var siblings =Array.prototype.slice.call(el.parentNode.children);for(var i = siblings.length; i--;){if(siblings[i]=== el){
siblings.splice(i,1);break;}}//谷歌浏览器,火狐浏览器,IE9+Array.prototype.filter.call(el.parentNode.children,function(child){return child !== el;});
Toggle Class
//JQUERY
$(el).toggleClass(className);//谷歌浏览器,火狐浏览器,IE8+if(el.classList){
el.classList.toggle(className);}else{var classes = el.className.split(' ');var existingIndex =-1;for(var i = classes.length; i--;){if(classes[i]=== className)
existingIndex = i;}if(existingIndex >=0)
classes.splice(existingIndex,1);else
classes.push(className);
el.className = classes.join(' ');}//谷歌浏览器,火狐浏览器,IE9+if(el.classList){
el.classList.toggle(className);}else{var classes = el.className.split(' ');var existingIndex = classes.indexOf(className);if(existingIndex >=0)
classes.splice(existingIndex,1);else
classes.push(className);
el.className = classes.join(' ');}//谷歌浏览器,火狐浏览器,IE10+
el.classList.toggle(className);
事件
Off
//JQUERY
$(el).off(eventName, eventHandler);//谷歌浏览器,火狐浏览器,IE8+function removeEventListener(el, eventName, handler){if(el.removeEventListener)
el.removeEventListener(eventName, handler);else
el.detachEvent('on'+ eventName, handler);}
removeEventListener(el, eventName, handler);//谷歌浏览器,火狐浏览器,IE9+
el.removeEventListener(eventName, eventHandler);
On
//JQUERY
$(el).on(eventName, eventHandler);//谷歌浏览器,火狐浏览器,IE8+function addEventListener(el, eventName, handler){if(el.addEventListener){
el.addEventListener(eventName, handler);}else{
el.attachEvent('on'+ eventName,function(){
handler.call(el);});}}
addEventListener(el, eventName, handler);谷歌浏览器,火狐浏览器,IE9+
el.addEventListener(eventName, eventHandler);
Ready
//JQUERY
$(document).ready(function(){});//谷歌浏览器,火狐浏览器,IE8+function ready(fn){if(document.readyState !='loading'){
fn();}elseif(document.addEventListener){
document.addEventListener('DOMContentLoaded', fn);}else{
document.attachEvent('onreadystatechange',function(){if(document.readyState !='loading')
fn();});}}//谷歌浏览器,火狐浏览器,IE9+function ready(fn){if(document.readyState !='loading'){
fn();}else{
document.addEventListener('DOMContentLoaded', fn);}
指定事件触发
//JQUERY
$(el).trigger('my-event',{some:'data'});//js谷歌浏览器,火狐浏览器,IE9+if(window.CustomEvent){varevent=newCustomEvent('my-event',{detail:{some:'data'}});}else{varevent= document.createEvent('CustomEvent');event.initCustomEvent('my-event',true,true,{some:'data'});}
el.dispatchEvent(event);
Trigger Native
//JQUERY
$(el).trigger('change');//谷歌浏览器,火狐浏览器,IE8+if(document.createEvent){varevent= document.createEvent('HTMLEvents');event.initEvent('change',true,false);
el.dispatchEvent(event);}else{
el.fireEvent('onchange');}//谷歌浏览器,火狐浏览器,IE9+// For a full list of event types: https://developer.mozilla.org/en-US/docs/Web/API/document.createEventvarevent= document.createEvent('HTMLEvents');event.initEvent('change',true,false);
el.dispatchEvent(event);
技巧
Array Each
//JQUERY
$.each(array,function(i, item){});谷歌浏览器,火狐浏览器,IE8+function forEach(array, fn){for(i =0; i < array.length; i++)
fn(array[i], i);}
forEach(array,function(item, i){});//谷歌浏览器,火狐浏览器,IE9+
array.forEach(function(item, i){});
深度扩展
//JQUERY
$.extend(true,{}, objA, objB);//谷歌浏览器,火狐浏览器,IE8+var deepExtend =function(out){out=out||{};for(var i =1; i < arguments.length; i++){var obj = arguments[i];if(!obj)continue;for(var key in obj){if(obj.hasOwnProperty(key)){if(typeof obj[key]==='object')
deepExtend(out[key], obj[key]);elseout[key]= obj[key];}}}returnout;};
deepExtend({}, objA, objB);
proxy
//JQUERY
$.proxy(fn, context);//谷歌浏览器,火狐浏览器,IE8+
fn.apply(context, arguments);//谷歌浏览器,火狐浏览器,IE9+
fn.bind(context);
bind
//jQuery
$.extend({}, objA, objB);//谷歌浏览器,火狐浏览器,IE8+var extend =function(out){out=out||{};for(var i =1; i < arguments.length; i++){if(!arguments[i])continue;for(var key in arguments[i]){if(arguments[i].hasOwnProperty(key))out[key]= arguments[i][key];}}returnout;};
extend({}, objA, objB);
Index Of
//JQUERY
$.inArray(item, array);//谷歌浏览器,火狐浏览器,IE8+function indexOf(array, item){for(var i =0; i < array.length; i++){if(array[i]=== item)return i;}return-1;}
indexOf(array, item);谷歌浏览器,火狐浏览器,IE9+
array.indexOf(item);
Is Array
//JQUERY
$.isArray(arr);//谷歌浏览器,火狐浏览器,IE8+
isArray =Array.isArray ||function(arr){returnObject.prototype.toString.call(arr)=='[object Array]';}
isArray(arr);//谷歌浏览器,火狐浏览器,IE9+Array.isArray(arr);
Map
//JQUERY
$.map(array,function(value, index){});//js谷歌浏览器,火狐浏览器,IE8+function map(arr, fn){var results =[];for(var i =0; i < arr.length; i++)
results.push(fn(arr[i], i));return results;}
map(array,function(value, index){});//谷歌浏览器,火狐浏览器,IE9+
array.map(function(value, index){});
Now
//JQUERY
$.now();//谷歌浏览器,火狐浏览器,IE8+newDate().getTime();//谷歌浏览器,火狐浏览器,IE9+Date.now();
Parse Html
//JQUERY
$.parseHTML(htmlString);谷歌浏览器,火狐浏览器,IE8+var parseHTML =function(str){var el = document.createElement('div');
el.innerHTML = str;return el.children;};
parseHTML(htmlString);谷歌浏览器,火狐浏览器,IE9+var parseHTML =function(str){var tmp = document.implementation.createHTMLDocument();
tmp.body.innerHTML = str;return tmp.body.children;};
parseHTML(htmlString);
解析 Json
//JQUERY
$.parseJSON(string);//谷歌浏览器,火狐浏览器,IE8+
JSON.parse(string);
Trim
//JQUERY
$.trim(string);//谷歌浏览器,火狐浏览器,IE8+string.replace(/^\s+|\s+$/g,'');//谷歌浏览器,火狐浏览器,IE9+string.trim();
Type
//JQUERY
$.type(obj);谷歌浏览器,火狐浏览器,IE8+Object.prototype.toString.call(obj).replace(/^\[object (.+)\]$/,"$1").toLowerCase();
ajax
新AJAX方法fetch()
基本Fetch用法
让我们先用一个例子来比较一下使用 XMLHttpRequest 和使用 fetch 之间的不同。我们要请求一个URL,获取JSON格式的返回结果。
原来的XMLHttpRequest
一个 XMLHttpRequest 请求需要两个监听器来捕捉 success 和 error 两种情形,而且需要调用 open() 和 send() 方法。
function reqListener(){var data = JSON.parse(this.responseText);
console.log(data);}function reqError(err){
console.log('Fetch Error :-S', err);}var oReq =newXMLHttpRequest();
oReq.onload = reqListener;
oReq.onerror = reqError;
oReq.open('get','./api/some.json',true);
oReq.send();
Fetch方法:
我们的 fetch 请求的代码基本上是这样的:
fetch('./api/some.json').then(function(response){if(response.status !==200){
console.log('Looks like there was a problem. Status Code: '+
response.status);return;}// Examine the text in the response
response.json().then(function(data){
console.log(data);});}).catch(function(err){
console.log('Fetch Error :-S', err);});
用fetch执行表单数据提交
在WEB应用中,提交表单是非常常见的操作,用fetch来提交表单数据也是非常简洁。
fetch里提供了 method 和 body 参数选项。
fetch(url,{
method:'post',
headers:{"Content-type":"application/x-www-form-urlencoded; charset=UTF-8"},
body:'foo=bar&lorem=ipsum'}).then(json).then(function(data){
console.log('Request succeeded with JSON response', data);}).catch(function(error){
console.log('Request failed', error);});
在Fetch请求里发送用户身份凭证信息
如果你想在fetch请求里附带cookies之类的凭证信息,可以将 credentials 参数设置成 “include” 值。
fetch(url,{
credentials:'include'})
JSON
//JQUERY
$.getJSON('/my/url',function(data){});//谷歌浏览器,火狐浏览器,IE8+var request =newXMLHttpRequest();
request.open('GET','/my/url',true);
request.onreadystatechange =function(){if(this.readyState ===4){if(this.status >=200&&this.status <400){// Success!var data = JSON.parse(this.responseText);}else{// Error :(}}};
request.send();
request =null;//谷歌浏览器,火狐浏览器,IE9+var request =newXMLHttpRequest();
request.open('GET','/my/url',true);
request.onload =function(){if(request.status >=200&& request.status <400){// Success!var data = JSON.parse(request.responseText);}else{// We reached our target server, but it returned an error}};
request.onerror =function(){// There was a connection error of some sort};
request.send();//谷歌浏览器,火狐浏览器,IE10+var request =newXMLHttpRequest();
request.open('GET','/my/url',true);
request.onload =function(){if(this.status >=200&&this.status <400){// Success!var data = JSON.parse(this.response);}else{// We reached our target server, but it returned an error}};
request.onerror =function(){// There was a connection error of some sort};
request.send();
Post
//JQUERY
$.ajax({
type:'POST',
url:'/my/url',
data: data
});//谷歌浏览器,火狐浏览器,IE8+var request =newXMLHttpRequest();
request.open('POST','/my/url',true);
request.setRequestHeader('Content-Type','application/x-www-form-urlencoded; charset=UTF-8');
request.send(data);
Request
//JQUERY
$.ajax({
type:'GET',
url:'/my/url',
success:function(resp){},
error:function(){}});//谷歌浏览器,火狐浏览器,IE8+var request =newXMLHttpRequest();
request.open('GET','/my/url',true);
request.onreadystatechange =function(){if(this.readyState ===4){if(this.status >=200&&this.status <400){// Success!var resp =this.responseText;}else{// Error :(}}};
request.send();
request =null;//谷歌浏览器,火狐浏览器,IE9+var request =newXMLHttpRequest();
request.open('GET','/my/url',true);
request.onload =function(){if(request.status >=200&& request.status <400){// Success!var resp = request.responseText;}else{// We reached our target server, but it returned an error}};
request.onerror =function(){// There was a connection error of some sort};
request.send();//谷歌浏览器,火狐浏览器,IE10+var request =newXMLHttpRequest();
request.open('GET','/my/url',true);
request.onload =function(){if(this.status >=200&&this.status <400){// Success!var resp =this.response;}else{// We reached our target server, but it returned an error}};
request.onerror =function(){// There was a connection error of some sort};
request.send();
特效
淡入淡出
//JQUERY
$(el).fadeIn();//谷歌浏览器,火狐浏览器,IE8+function fadeIn(el){var opacity =0;
el.style.opacity =0;
el.style.filter ='';varlast=+newDate();var tick =function(){
opacity +=(newDate()-last)/400;
el.style.opacity = opacity;
el.style.filter ='alpha(opacity='+(100* opacity)|0+')';last=+newDate();if(opacity <1){(window.requestAnimationFrame && requestAnimationFrame(tick))|| setTimeout(tick,16);}};
tick();}
fadeIn(el);//谷歌浏览器,火狐浏览器,IE9+function fadeIn(el){
el.style.opacity =0;varlast=+newDate();var tick =function(){
el.style.opacity =+el.style.opacity +(newDate()-last)/400;last=+newDate();if(+el.style.opacity <1){(window.requestAnimationFrame && requestAnimationFrame(tick))|| setTimeout(tick,16)}};
tick();}
fadeIn(el);//谷歌浏览器,火狐浏览器,IE10+
el.classList.add('show');
el.classList.remove('hide');.show {
transition: opacity 400ms;}.hide {
opacity:0;}
Hide
//JQUERY
$(el).hide();//谷歌浏览器,火狐浏览器,IE8+
el.style.display ='none';
Show
//JQUERY
$(el).show();//谷歌浏览器,火狐浏览器,IE8+
el.style.display ='';
jquery属性的相关js实现方法的更多相关文章
- jQuery 属性操作 - addClass() 和 removeClass() 方法
实例 向第一个 p 元素添加一个类: $("button").click(function(){ $("p:first").addClass("int ...
- jquery动态加载JS【方法getScript】的改进
http://www.cnblogs.com/cuitsl/archive/2012/11/15/2771549.html
- js进阶 13-6 jquery动画效果相关常用函数有哪些
js进阶 13-6 jquery动画效果相关常用函数有哪些 一.总结 一句话总结:animate(),stop(),finish(),delat()四个. 1.stop()方法的基本用法是什么(sto ...
- js进阶课程 12-9 jquery的事件对象event的方法有哪些?
js进阶课程 12-9 jquery的事件对象event的方法有哪些? 一.总结 一句话总结:三组六个,阻止默认事件一组,阻止冒泡一组,阻止冒泡和剩余事件一组. 1.事件的默认动作指什么? 比如点a标 ...
- js进阶 11-2 jquery属性如何操作
js进阶 11-2 jquery属性如何操作 一.总结 一句话总结:jquery中的属性用attr方法表示.jquery中都是方法. 1.jquery中的属性的增删改查操作? 只需要两个方法, at ...
- jQuery 属性操作 - val() 方法
val() 方法返回或设置被选元素的值. 元素的值是通过 value 属性设置的.该方法大多用于 input 元素. 如果该方法未设置参数,则返回被选元素的当前值. <html> < ...
- jQuery 属性操作 - attr() 方法
定义和用法 attr() 方法设置或返回被选元素的属性值. 根据该方法不同的参数,其工作方式也有所差异. 实例1 设置被选元素的属性和值. <html><head><sc ...
- 使用jQuery异步传递含复杂属性及集合属性的Model到控制器方法
Student类有集合属性Courses,如何把Student连同集合属性Courses传递给控制器方法? public class Student { public ...
- js进阶 12-13 jquery中one方法和trigger方法如何使用
js进阶 12-13 jquery中one方法和trigger方法如何使用 一.总结 一句话总结: 1.one()方法和on()方法的区别是什么? 除了one()只执行一次,其它和on()一模一样,包 ...
随机推荐
- 2快速掌握OMD
我们已经知道使用ArcGIS Engine开发,也就意味着我们要和接口打交道,ArcGIS Engine中提供的接口和类加起来估计上万,但是用过ArcGIS Engine的人,知道这个数字不为过.Ar ...
- 说说Core Animation
前言 本次分享将从以下方面进行展开: 曾被面试官问倒过的问题:层与视图的关系 CALayer类介绍及层与视图的关系 CAShapeLayer类介绍 UIBezierPath贝塞尔曲线讲解 CoreAn ...
- hive第二篇----hive中partition如何使用
一.背景 1.在Hive Select查询中一般会扫描整个表内容,会消耗很多时间做没必要的工作.有时候只需要扫描表中关心的一部分数据,因此建表时引入了partition概念. 2.分区表指的是在创建表 ...
- Linux命令 理解
RPM常用命令参数列表 1.安装一个包 # rpm -ivh 2.升级一个包 # rpm -Uvh [注意U一定要大写] -i 安装 -U 升线安装 -h 以#显示安装进度 -v 显示附加 ...
- 加载window事件
$(document).ready()和window.onload的区别 发表于 2012-08-29 由 admin 以浏览器装载文档为例,在页面加载完毕后,浏览器会通过JavaScript为DOM ...
- (简单) POJ 3254 Corn Fields,状压DP。
Description Farmer John has purchased a lush new rectangular pasture composed of M by N (1 ≤ M ≤ 12; ...
- 012-ViewState状态保持
客户端的状态保持方案:ViewState.隐藏域.Cookies.控件状态.URL查询参数服务端的状态保持方案:Session(会话).Application.Caching(缓存).DataBase ...
- module_param()函数
1.定义模块参数的方法: module_param(name, type, perm); 其中,name:表示参数的名字; type:表示参数的类型; perm:表示参数的访问权限; ...
- 深入理解yield(转)
yield的英文单词意思是生产,刚接触Python的时候感到非常困惑,一直没弄明白yield的用法.只是粗略的知道yield可以用来为一个函数返回值塞数据,比如下面的例子: def addlist(a ...
- 把div 当文字来进行布局控制
两边对齐 text-align: justify; text-justify: distribute-all-lines;/*ie6-8*/ text-align-last: justify;/* i ...