這份筆記把 jQuery 針對元素的操作整理成三大塊:集合基礎操作、如何精準選到目標元素、以及實際處理 DOM。適合當作随手查閱的參考表。
$() 回傳的是 jQuery 物件集合。取出集合中的成員有幾種方式:
// 用索引取原生 JavaScript 元素
var temp = $('img[alt]')[0]
// 用 get 方法取原生元素
var temp = $('img[alt]').get(0)
// 用 eq 取 jQuery 物件元素
$('img[alt]').eq(0)
$('img[alt]').first()
$('img[alt]').last()
// 整個集合轉成 JavaScript 陣列
var arr = $('label+button').toArray()
取得索引:
var n = $('img').index($('img#id')[0]) // 注意:參數是 JavaScript 元素
var n = $('img').index('img#id') // 等同上一行,找不到回傳 -1
var n = $('img').index() // 取得 img 在同層元素中的索引
擴充集合:
$('img[alt],img[title]') // 用逗號併入
$('img[alt]').add('img[title]') // 用 add 方法
$('img[alt]').addClass('thickBorder').add('img[title]').addClass('')
$('p').add('<div></div>') // 加入新建立元素
縮小集合:
$('img[title]').not('[title*=pu]')
$('img').not(function(){ return !$(this).hasClass('someClassname') })
$('td').filter(function(){ return this.innerHTML.match(/^\d+$/) }) // 只留含數字的 td
$('*').slice(0, 4) // 前 4 個元素組成的集合
$('*').slice(4) // 從第 4 個之後
$('div').has('img[alt]')
轉換與遍歷:
var allIds = $('div').map(function(){
return (this.id == undefined) ? null : this.id;
}).get(); // get() 讓結果成為 JavaScript 陣列
$('img').each(function(n){
this.alt = '這是第[' + n + ']張圖片,圖片的id是' + this.id;
});
$([1,2,3]).each(function(){ alert(this); })
依關係取得集合:
$(this).closest('div') // 最近的祖先 div
$(this).siblings('button[title="Close"]') // 所有同層,不含自己
$(this).children('.someclassname') // 所有子元素
$(this).contents() // 包含文字節點,可讀 iframe 內容
$(this).next('.someclassname') // 下一個同層
$(this).nextAll() // 後面所有同層
$(this).nextUntil('.someclassname') // 後面同層直到遇到目標
$(this).offsetParent() // 最近的定位父元素
$(this).parent() // 直接父元素
$(this).parents() // 所有祖先
$(this).parentsUntil() // 祖先直到目標
$(this).prev() / $(this).prevAll() / $(this).prevUntil()
其他常用:
$(this).find('p span') // 找出符合的後代
var hasImg = $('*').is('img'); // 判斷集合是否符合選擇器
$().hide()
$().addClass('')
$().html('')
$('a').size() // 元素數量
$.trim()
$(document).ready(function(){});
$(function(){});
建立與擴充:
$('<p></p>').insertAfter();
$('<img>', {
src: '', alt: '', title: '',
click: function(){}
}).css({ cursor: 'pointer', border: '' })
.append('');
$.fn.disable = function(){
return this.each(function(){
if (this.disabled != null) this.disabled = true;
})
};
$('').disable();
存在性測試建議寫成 if (item != null),因為它能同時排除 null 與 undefined,比寬鬆的 if (item) 語意更精確。
依標籤、id、class:
$('a')
$('#id')
$('.someclassname')
$('a#id.someclassname') // 多重條件
$('div,span') // 多選一
$('p a.someclassname') // 後代
$('ul.myList > li') // 直接子元素
依屬性:
$('a[href^="https://"]') // 開頭
$('a[href$=".pdf"]') // 結尾
$('form[method]') // 含該屬性
$('input[type="text"]')
$('input[name!=""]') // 不含
$('a[href*="some"]') // 包含
依位置:
$('li:first') $('li:last')
$('li:even') $('li:odd')
$('li:eq(n)') $('li:gt(n)') $('li:lt(n)')
$('ul:first-child') $('ul:last-child')
$('ul:nth-child(n)') $('ul:only-child')
$('ul:nth-child(even)') $('ul:nth-child(5n+1)')
依過濾器:
$('input:not(:checkbox)')
$('img:not([src*="dog"])')
$('div:has(span)')
$('tr:has(img[src$="pu.png"])')
$('tr:animated')
$('input:button') $('input:checkbox') $('input:file')
$('input:hidden') $('input:image') $('input:password')
$('input:radio') $('input:reset') $('input:submit')
$('input:text') $('input:disabled') $('input:enabled')
(':header') (':input') (':parent')
('span:contains(food)') ('div:visible') ('.cls:selected')
屬性操作:
$('*').each(function(n){ this.id = this.tagName + n; })
$('').attr('') // 取值
$('input').attr({ value: '', title: '' }) // 同時設多個
$('*').attr('title', function(index, previousValue){
return previousValue + ' I am element ' + index + ' and my name is ' + this.id;
})
$('p').removeAttr('value')
$('a[href^="https://"]').attr('target', "_blank")
$("form").submit(function(){
$(":submit", this).attr("disabled", "disabled"); // 避免重複送出
})
class 操作:
$('#id').addClass('')
$('#id').removeClass('')
$('#id').toggleClass('') // 有則移除、無則加上
$('p:first').hasClass('')
$('p:first').is('')
樣式與尺寸:
$('div.someclassname').css(function(index, currentWidth){
return currentWidth + 20;
});
$('div').css({ cursor: 'pointer', border: '1px solid black' });
$(div).width(500)
$('div').height() $('div').innerHeight() $('div').innerWidth()
$('div').outerHeight(true) $('div').outerWidth(false)
定位與滾動:
$('p').offset() // 相對於文件的座標
$('p').position() // 相對於定位父元素的偏移
$('p').scrollLeft() $('p').scrollLeft(value)
$('p').scrollTop() $('p').scrollTop(value)
內容讀寫:
$('p').html() $('p').html('') $('p').text() $('p').text('')
插入位置:
$('p').append('<b>some text</b>') // 元素內、尾端
$('p').append($(a.someclassname))
$("p").prepend() // 元素內、頭部
$("span").before() // 元素外、前面
$("span").after() // 元素外、後面
appendTo(targets) prependTo(targets)
insertBefore(targets) $('<p></p>').insertAfter('p img')
包裹與刪除:
$('a.someclassname').wrap("<div class='hello'></div>")
$('a.someclassname').wrap($("div:first")[0])
$('a.someclassname').wrapAll()
$('a.someclassname').wrapInner()
$('a.someclassname').unwrap()
$('.classname').remove() // 連事件與資料一起移除
$('.classname').detach() // 保留事件與資料
$('.classname').empty() // 只清空內容
複製與替換:
$('img').clone().appendTo('p.someclassname')
$('ul').clone().insertBefore('#id')
$('img[alt]').each(function(){
$(this).replaceWith('<span>' + $(this).attr('alt') + '</span>');
})
$("p").replaceAll("<b></b>")
表單值:
$('[name="radioGroup"]:checked').val() // 未選中時回傳 undefined
var checkboxValues = $('[name="checkboxGroup"]:checked').map(function(){
return $(this).val();
}).toArray();
// 多選 select
$('#list').val() // 回傳陣列
$('input').val(['one','two','three']) // 符合者被勾選
把這份對照表放進書籤,寫 jQuery 時大部分操作都能直接查到對應方法,不必再來回翻文件。