jQuery 常用 $() 建立物件集合,並可透過索引、get、eq、first、last 等方式取得元素。
$('img[alt]')[0]
$('img[alt]').get(0)
$('img[alt]').eq(0)
若要轉成 JavaScript 陣列,可以使用:
var arr = $('label+button').toArray();
依標籤:$('a')
依 id:$('#id')
依 class:$('.someclassname')
依屬性:$('a[href^="https://"]')
依位置:$('li:first')、$('li:last')、$('li:eq(n)')
取得屬性:$('').attr('')
設定屬性:$('*').attr('title', 'value')
移除屬性:$('p').removeAttr('value');
加入 class:$('#id').addClass('')
移除 class:$('#id').removeClass('')
切換 class:$('#id').toggleClass('')
$('div').width()
$('div').height()
$('div').innerHeight()
$('div').outerHeight(true)
$('p').offset()
$('p').position()
取得 HTML:$('p').html()
設定 HTML:$('p').html('')
取得文字:$('p').text()
設定文字:$('p').text('')
附加內容:append()、prepend()、before()、after()
刪除元素:remove()、detach()、empty()
複製元素:clone()
替換元素:replaceWith()
取得單選值:$('[name="radioGroup"]:checked').val()
取得多選值:
var values = $('[name="checkboxGroup"]:checked').map(function(){ return $(this).val(); }).toArray();
這些基礎用法幾乎涵蓋了日常 jQuery 開發中最常見的操作。