JQuery 學習筆記 02

學習Blog
7 min readSep 10, 2020

--

節點篩選的方法

例子
// filter - 過濾選擇的對象是否 有 該條件
$('div').filter('.box') // 選擇到div1
// not - 過濾選擇的對象是否 沒有 該條件
$('div').not('.box') // 選擇到div2
// has - 過濾選擇的對象的 子節點是否有 該條件
$('div').has('.box') // 選擇到div2,因為它裡面的節點有一個class為box

節點選擇的方法

// prev 找到前一個節點
$('h3').prev() // 得到P標籤
// next 找到下一個節點
$('h3').next() // 得到em標籤
// find 找到符合條件的子節點
$('li') // 所有li都會被選到
$('ul').find('li') // 只有ul底下的li才會被選到
$('ul li') // find方法等同於本寫法
// find也可以設定特定的值來篩選
$('ul').find('.box') //選ul底下class為box的子元素
$('ul').find('[name="hello"]') // 選ul底下name屬性為hello的子元素
// index 回傳該元素在目前的位置,從0開始,如果沒有該節點,回傳-1
$('ul li').index() // 回傳0
// eq 可以指定index來尋找特定的元素,可以寫在外面或CSS選擇器裡面
$('li').eq(3) // 選擇ol標籤中的第一個li標籤
$('li:eq(3)') // 等於上面的寫法

屬性方法

// attr用於顯示該元素屬性的值
alert($('div').attr('id')) //div1
alert($('div').attr('title')) //hello
alert($('div').attr('class')) // box
// 也可以用來修改、設定屬性值
$('div').attr('class','box22222')
// 一次改多種屬性方法,以物件形式傳入,key可以是字串,也可以不是$('div').attr({
class: 'box3333',
title: 'xxxxx',
'yyy': 'abc'
})

長度測量

CSS設定
// width()、innerWidth、outWidth():取得節點的寬度
// height()、innerHeight、outHeight():取得節點的高度
alert($('#div1').css('width')) //100px
// width
alert($('#div1').width()) // 100
// width
alert($('#div1').innerWidth()) //104
// width + padding
alert($('#div1').outerWidth()) // 106
// width + border + padding
alert($('#div1').outerWidth(true)) //112
// width + border + padding + margin

節點位置操作

insertBefore()      //等於JS的 before()insertAfter()       //等於JS的 after()appendTo()          //等於JS的 append()、appendChild()prependTo()         //等於JS的 prepend()remove()
// 將div安插到span之前,這個Before是指span的before
$('div').insertBefore($(span))
// div前面節點是span,這個Before是指div的before
$('div').before($(span))

事件監聽、委派

// JQuery 可以保留所有事件與指派對象,不會覆蓋
$('#div1').click(()=>{ alert(1) }) // alert 1
$('#div1').click(()=>{ alert(2) }) // alert 2
// 基本做法,綁定一個函式
$('#div1').on('click',function(){ alert('hello') })
// 一個對象綁定多個事件
let i = 0
$('#div1').on('click mouseover', function () {
$(this).html(i++)
})
// 不同事件綁定不同函式
$('#div1').on({
click: function () {
alert('點擊')
},
mouseover: function () {
$(this).css('backgroundColor', 'orange')
},
mouseout: function () {
$(this).css('backgroundColor', 'blue')
},
})
// 另外指定觸發對象
// 事件委託 on('事件名稱','觸發對象(使用CSS選擇器)',執行的函式)
$('ul').on('click', 'li', function () {
$(this).css('backgroundColor', 'blue')
})
// 新增節點,直接寫上節點
let i = 6
$('#btn1').click(function () {
const node = `<li>${i++ * 111}</li>`
$(node).appendTo('ul')
})
// 取消事件
$('#div1').click(show)
function show() {
alert('show')
}
$('#cancel').click(function () {
//取消所有綁定的事件
$('#div1').off()
//取消特定事件
$('#div1').off('click')
//取消特定事件+函式
$('#div1').off('click', show)
})

取得頁面高度

// 取得目前scroll高度
$(document).scrollTop()
// 配合animate,可以做出scroll to top 特效
$("html, body").animate({ scrollTop: 0 }, 500)
// 計算window的高度、寬度,論怎樣移動頁面,可以讓節點固定在同一位置

--

--

學習Blog
學習Blog

No responses yet