关于此模块分为三个部分来写:
- 元素属性操作方法
- 元素CSS类操作方法
- 元素HTML代码/文本/值操作方法
一:元素属性操作方法(下面读取,设置或移除的属性都是要在行内有的属性)
1.attr( ) 设置或读取元素属性,可读可写,检索HTML属性
//语法
$(selector).attr(attribute) //读取
$(selector).attr(attribute,value) //设置
$(selector).attr(attribute,function(index,oldvalue)) //index为选择器index值,oldvalue为原来属性值
$(selector).attr({attribute:value, attribute:value ...})
//eg
$('img').attr('width')
$('img').attr('width','300')
$('img).attr('width',function(index,oldvalue){
return oldvalue-50;
})
$('img').attr({'width':'300','height':'300'})
2.removeAttr( ) 移除元素属性
//语法
$(selector).removeAttr(attribute)
//eg
$('p').removeAttr('id')
3.prop( ) 设置或读取元素属性,可读可写,检索DOM属性
//语法
$(selector).prop(property) //读取
$(selector).prop(property,value) //设置
$(selector).prop(property,function(index,currentvalue)) //index为选择器index值,oldvalue为原来属性值
$(selector).prop({property:value, property:value ...})
//eg
$('img').attr('width')
$('img').attr('width','300')
$('img').attr('width',function(index,oldvalue){
return oldvalue-50;
})
$('p').attr({'width':'300','height':'300'})
4.removeProp( ) 移除元素属性
//语法
$(selector).removeProp(property)
//eg
$('p').removeProp('id')
二:元素CSS类操作方法
1.addClass( ) 给元素添加一个或多个类
//语法
$(selector).addClass(class)
$(selector).addClass(function(index,oldclass))
//eg
$('p').addClass('intro')
2.removeClass( ) 删除元素一个或多个类
//语法
$(selector).removeClass(class)
$(selector).removeClass(function(index,oldclass))
//eg
$('p').removeClass('intro')
3.toggleClass( ) 切换添加或者移除元素一个或多个类
//语法
$(selector).toggleClass(class)
$(selector).toggleClass(classname,function(index,currentclass),switch) //switch参数控制只添加(true)或只删除(false)类
//eg
$('p').toggleClass('intro')
$('p').toggleClass('intro',false)
三:元素HTML代码/文本/值操作方法
1.html( ) 设置或返回第一个匹配元素的html内容,不包含标签
//语法
$(selector).html() //读取
$(selector).html(content) //设置
$(selector).html(function(index,oldcontent))
//eg
$('p').html()
$('p').html('Hello <b>world!</b>') //Hello world,world会加粗,标签会起作用
2.text( ) 设置或返回所有匹配元素的html内容,包含标签
//语法
$(selector).text() //读取
$(selector).text(content) //设置
$(selector).text(function(index,oldcontent))
//eg
$('p').text()
$('p').text('Hello <b>world!</b>') //Hello <b>world!</b>
3.val( ) 返回第一个匹配元素的 value 属性的值,主要用于表单元素
//语法
$(selector).val() //读取
$(selector).val(value) //设置
$(selector).text(function(index,oldvalue))
//eg
$('input').val()
$('input').val('设置表单元素value属性值') //Hello <b>world!</b>
以上通过函数进行操作中的index值皆表示选择器的 index 位置,old表示元素之前的,current表示当前,这些参数都是可选