捕获
DOM(Document Object Model)定义访问HTML和XML文档的标准 text()返回所选元素的文本内容 html()返回所选元素的内容 val()设置或返回表单字段的值 attr() 获取属性 对于 HTML 元素本身就带有的固有属性,在处理时,使用 prop 方法。 对于 HTML 元素我们自己自定义的 DOM 属性,在处理时,使用 attr 方法。 如何获取:
<!DOCTYPE html>
< html>
< head>
< meta charset = " utf-8" >
< script src = " https://cdn.staticfile.org/jquery/1.10.2/jquery.min.js" >
</ script>
< script>
$ ( document) . ready ( function ( ) {
$ ( "#btn1" ) . click ( function ( ) {
alert ( "Text: " + $ ( "#test" ) . text ( ) ) ;
} ) ;
$ ( "#btn2" ) . click ( function ( ) {
alert ( "HTML: " + $ ( "#test" ) . html ( ) ) ;
} ) ;
} ) ;
</ script>
</ head>
< body>
< p id = " test" > 这是段落中的 < b> 粗体</ b> 文本。</ p>
< button id = " btn1" > 显示文本</ button>
< button id = " btn2" > 显示 HTML</ button>
</ body>
</ html>
<!DOCTYPE html>
< html>
< meta charset = " utf-8" >
< head>
< script src = " https://cdn.staticfile.org/jquery/1.10.2/jquery.min.js" >
</ script>
< script>
$ ( document) . ready ( function ( ) {
$ ( "button" ) . click ( function ( ) {
alert ( "值为: " + $ ( "#test" ) . val ( ) ) ;
} ) ;
} ) ;
</ script>
</ head>
< body>
< p> 名称: < input type = " text" id = " test" value = " 菜鸟教程" > </ p>
< button> 显示值</ button>
</ body>
</ html>
jQuery设置 -attr()设置属性
<!DOCTYPE html>
< html>
< head>
< meta charset = " utf-8" >
< script src = " https://cdn.staticfile.org/jquery/1.10.2/jquery.min.js" >
</ script>
< script>
$ ( document) . ready ( function ( ) {
$ ( "button" ) . click ( function ( ) {
$ ( "#runoob" ) . attr ( {
"href" : "http://www.runoob.com/jquery" ,
"title" : "jQuery 教程"
} ) ;
title = $ ( "#runoob" ) . attr ( 'title' ) ;
$ ( "#runoob" ) . html ( title) ;
} ) ;
} ) ;
</ script>
</ head>
< body>
< p> < a href = " //www.runoob.com" id = " runoob" > 菜鸟教程</ a> </ p>
< button> 修改 href 和 title</ button>
< p> 点击按钮修改后,可以查看 href 和 title 是否变化。</ p>
</ body>
</ html>
回调函数 attr(),html(),text(),val()的回调函数均有两个参数:被选元素列表中当前元素的下标,以及原始值,
$("#btn1").click(function(){
$("#test1").text(function(i,origText){
return "旧文本: " + origText + " 新文本: Hello world! (index: " + i + ")";
//""中的内容为新的返回值:您希望使用的字符串
});
});
添加元素和删除元素
append()在被选元素的结尾插入元素 prepend()在被选元素的开头插入内容 after()在被选元素之后插入内容 before()在被选元素之前插入内容 插入多元素:
< script>
function appendText ( ) {
var txt1= "<p>文本。</p>" ;
var txt2= $ ( "<p></p>" ) . text ( "文本。" ) ;
var txt3= document. createElement ( "p" ) ;
txt3. innerHTML= "文本。" ;
$ ( "body" ) . append ( txt1, txt2, txt3) ;
}
</ script>
< script>
$ ( document) . ready ( function ( ) {
$ ( "#btn1" ) . click ( function ( ) {
$ ( "img" ) . before ( "<b>之前</b>" ) ;
} ) ;
$ ( "#btn2" ) . click ( function ( ) {
$ ( "img" ) . after ( "<i>之后</i>" ) ;
} ) ;
} ) ;
</ script>
删除元素
remove() - 删除被选元素(及其子元素):可以接受一个参数,允许对被删元素进行过滤($(“p”).remove(".italic"); 即移除class值为italic的元素)。 empty() - 从被选元素中删除子元素
CSS类
css()方法
设置css属性:css(“propertyname”,“value”); 设置多个css属性:css({“propertyname”:“value”,“propertyname”:“value”,…});
css尺寸 尺寸如下图所示六个方法 width() height() innerWidth() innerHeight() outerWidth() outerHeight()
菜鸟教程