jQuery基础(二)

jQuery 操作 DOM

捕获

text( ) 返回文本内容

html( ) 返回元素内容(包括html标记)

val( ) 返回字段的值

attr( ) 获取属性值

1
$(selector).attr("href")

同时以上方法均可以为元素赋新值

1
2
3
4
5
6
7
8
9
$(selector).text("This is new Value")
$(selector).html("<b>This is new Value</b>")
$(selector).val("This is new Value")
$(selector).attr("href", "https://glorylin0704.github.io")
// attr 可以设置多个属性
$(selector).attr({
"href": "https://glorylin0704.github.io/",
"title": "博客"
})

同时以上方法均有回调函数,两个参数,第一个是当前元素的下标,第二个是原始的值,函数返回值作为新值

1
2
3
4
5
6
7
$(selector).xxx(function(i, oldText){
return newValue
})
$(selector).attr("href", function(i, oldText){
return newValue
})

控制元素

append( ) 在被选元素的结尾插入内容

prepend( ) 在被选元素的开头插入内容

after( ) 在被选元素之后插入内容

before( ) 在被选元素之前插入内容

1
$(selector).xxx(" ")

append / prepend 是在选择元素内部嵌入
after / before 是在元素外面追加


remove( ) 删除被选元素及其子元素

empty( ) 从被选元素中删除子元素

1
2
3
4
$(selector).xxx()
//过滤被删除的元素
$(selector).remove(".who")

控制 CSS

addClass( ) 向被选元素添加一个或多个类

removeClass( ) 从被选元素删除一个或多个类

toggleClass( ) 对被选元素进行添加/删除类的切换操作

1
$(selector).xxx("")

css( ) 获取或设置被选元素的css

1
2
3
4
5
6
7
8
$(selector).css("background-color")
//返回元素的背景色
$(selector).css({
"background-color": "red",
"font-size": "20px"
})
//设置元素的css值

获取尺寸

width( ) height( )

content 的宽高

innerWidth( ) innerHeight( )

content + padding 的宽高

outerWidth( ) outerHeight( )

content + padding + border 的宽高

outerWidth(true) + outerHeight(true)

content + padding + border + margin 的宽高

1
$(selector).xxx()

Ajax

get( ) 从指定的资源请求数据

post( ) 向指定的资源提交处理的数据

现在的 Ajax 可以使用 Promise

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
// get(URL. callback);
$("button").click(function(){
$.get("/somewhere").catch(suc => {
//succeed
}).catch(err => {
//failed
})
})
//post(URL, data, callback)
$("button").click(function(){
$.post("/somewhere",{
name: "Glory",
age: "22"
}).then(suc => {
//succeed
}).catch(err => {
//failed
})
})