jQuery 開發筆記


  1. 元素選取
    1. 常見的選取方式
    2. 根據 input 的 name 選取
    3. 選取相同 Id 字串開頭的元素
    4. 取出所有的 h2, h3 標籤
  2. 元素操作
    1. 取出元素值 (val, text, html, attr)
    2. 元素賦值 (val, text, html, attr)
    3. 操作元素的 CSS (addClass, removeClass, toggleClass, css)
    4. 在元素上綁定資訊 (data)
    5. 對 jQuery Select Collection 逐一元素操作 (each)
    6. 將 jQuery 物件轉為 DOM 物件
  3. 事件行為
    1. 點擊 (Click)
    2. 全域聆聽鍵盤輸入 (KeyPress)
    3. 移除元素 (Hide, Remove)
  4. Ajax
    1. load file html content
    2. ajax 並指定 callBack 行為
  5. 其他
    1. IE11 出現不支援 AddEventListner 時的處理方法
    2. 取得物件的所有 Key
    3. 控制 DataTables 的搜尋行為

jQuery 的常用操作筆記,其次每次的使用需求都很簡單,只是有時候稍微卡住就要花費時間搜尋與測試,索性將常用的行為作成筆記,方便檢索。

元素選取

常見的選取方式

$('a');
$('#id');
$('.className');
$('#id:first');
$('.parentClass > .childClass');

根據 input 的 name 選取

$('input[name="Name"]');

⚠️ 注意 name 的選取有 Case Sensitive

選取相同 Id 字串開頭的元素

$('[id^=Element]')

取出所有的 h2, h3 標籤

Pure JS

document.querySelectorAll('h2 , h3').forEach(x => console.log(x.tagName, x.textContent))

元素操作

取出元素值 (val, text, html, attr)

$('#id').val()
$('#id').text()
$('#id').html()
$('#id').attr('data-property')

元素賦值 (val, text, html, attr)

$('#id').val('Value')
$('#id').text('Text')
$('#id').html('<p>lorem ipsum</p>')
$('#id').attr('data-property', val)

操作元素的 CSS (addClass, removeClass, toggleClass, css)

$('#id').addClass('className')
$('#id').removeClass('className')
$('#id').toggleClass('className') //add if Not exists, remove If exists
$('#id').css('background-color') //get element specific css attribute value
$('#id').css('background-color', 'red') //get element specific css attribute value

在元素上綁定資訊 (data)

$('#id').data(key, value)

jQuery API - data

對 jQuery Select Collection 逐一元素操作 (each)

$( "li" ).each(function( index ) {
  console.log( index + ": " + $( this ).text() );
});

jQuery API - each

將 jQuery 物件轉為 DOM 物件

$('selector').get() //to js array
$('selector').get(1) //get first element of js array

事件行為

點擊 (Click)

$('#id').click() //對 #id 元素進行點擊
$('#id').click(function(){
  ...
}); //對 #id 元素註冊被點擊的 callback function

更多關於滑鼠的事件

全域聆聽鍵盤輸入 (KeyPress)

$(function() {
   $(window).keypress(function(e) {
      console.log(e.which);
   });
});

更多關於鍵盤事件

移除元素 (Hide, Remove)

$('#id').hide() //still can be see by html source, add style display none
$('#id').remove()

Ajax

load file html content

$(".btn").click(function(){
  $("#p1").load("htmlContent.txt");
  $("#p2").load("htmlContent.html");
});

ajax 並指定 callBack 行為

$('#id').load(url, function(res, status, xhr){
  ...
})

Load

其他

IE11 出現不支援 AddEventListner 時的處理方法

Html 加入以下 meta:

<meta http-equiv="X-UA-Compatible" content="IE=edge, chrome=1" />

取得物件的所有 Key

Object.keys(obj)

控制 DataTables 的搜尋行為

$('.dataTableFilter').click(function () {
    $('.dataTableEnable').DataTable().search($(this).html()); //modify search text
    $('.dataTableEnable').DataTable().search($(this).html()).draw(); //implement search
})

DataTables