针对DOM的不同实践

2018-11-03  本文已影响10人  好心态

集合分为兄弟节点集合(nextAll,siblings,index),针对结果集(filter,first,eq,not,has,slice),针对子孙节点(find)

jQuery选择器 jQuery CSS JS定位
prev+ next() prev+next nextElementSibling
prev([expr]) previousElementSibling
prev~siblings nextAll(filter) prev~siblings
first first() 自动选取第一个 querySelector()
:eq(6) eq(6) 从0开始计数
交叉选择器 filter(expr/fn)
:not(selector) not(selector)
返回Html节点 :root document.documentElement​
子孙后代节点
:first-child :first-child firstChild
nth-child(n) children(':eq(n)') n从1开始计数
parent> children(filter) parent> children
contents() childNodes
对子孙进行寻找 find(slt) querySelectorAll
[name=prig] 获取所有符合元素 getElementsByName()
:has() has() 是否拥有某个后代
parent([expr]) jq集合每个人的爸爸 parentElement

jQuery选择器会在集合中每个元素上进行筛选,并将选择出来的元素进行合并
而DOM只能对单个element元素逐一操作

jQuery 与 Javascript操作对比

节点操作

Jquery Javascript
子节点操作
append append
prepend prepend
处于链式操作考虑
appendTo
prependTo
兄弟节点操作
clone() cloneNode()
深度复制
clone(true) cloneNode(true)
after(content) after()
$(content).insertAfter(e) 被动操作
e.remove([expr]) e.remove()
detach() 返回所有子节点与事件
子节点自动向上升级 removeNode(false)
返回删除节点 e.removeNode(true)
replaceWith() replaceNode()
replaceAll() 反向操作
swapNode()
Class操作
addClass() add()
removeClass() remove()
toggleClass() classList.toggle()
hasClass() classList.contains()
属性操作
attr({}) .property;setAttribute()
removeAttr() removeAttribute()
prop() getPropertyValue()
css({}) .style.backgroundColor
html() .innerHTML
text() .text
val([]) .value
data('penchant') dataset.penchant
removeData("greeting")
控制
$(window).scrollTop() window.scrollY
offset().top .offsetTop
each(fun) NodeList,数组:forEach()
map(callback) 返回匹配jq对象数组
事件
click() click()
工具
$.makeArray Array.from
$.type(4) typeof(4)
$.isNumeric isNaN
$.isArray Array.isArray
$.inArray("John", arr) indexOf
$.merge(arr1,arr2) arr1.concat(arr2)

val()用来选择select的option,val([2,3])实现多选.val()返回 ["2", "3"]

jq.height()=内容
clientHeight=内容+padding 窗口可见的高度<==>innerHeight()
scrollHeight=内容(不可见滚动内容高度)+padding
offsetHeight=内容+padding+border <==>outerHeight()
对比
forEach方法中的function回调有三个参数:第一个参数是遍历的数组内容,第二个参数是对应的数组索引,第三个参数是数组本身
因此:
[].forEach(function(value,index,array){//code something});
等于
$.each([],function(index,value,array){//code something})

NodeList:
document.childNodes.forEach(function(v,k,l){console.info(v);console.info(k);console.info(l)})

each:
$("li").each(function(){ alert($(this).text())});
$(selector).each(function(index,element))
element - 当前的元素(也可使用 "this" 选择器)

jQuery独有

选择器 描述
兄弟定位
siblings(filter)
eq(index) 在结果集中定位,可为负数
nextUtil(selector)
祖先定位
closest()
index() 兄弟节点排行
parentsUtil(selector) 选择器之前父元素
parents(filter)
has(descendent) 而contains()返回的是布尔值
包裹
wrap() 每个元素单独包裹
wrapAll() 最外层包裹
wrapInner() 最外包裹子节点
unwrap() 删除最外包裹
操作
is(expr) 只判断第一个元素
empty() 清空子元素
slice(start[,end]) js数组slice
上一篇下一篇

猜你喜欢

热点阅读