JQuery笔记整理
- 格式:doc
- 大小:115.50 KB
- 文档页数:23
Jquery学习笔记Jquery 学习笔记--方法大集合【转载】2009-02-25 10:40本笔记翻译自:可视JQuery1.$()的用法1.1 $(html) =>根据HTML参数动态建立一个jquery对像例子:$(”<div>hello</div>”).appendTo(”#body”),动态的创建一个div element插入到ID为body的element中去1.2 $(element) =>把节点对像转化成一个jquery对像例子:$(document.body).background( “black” );1.3 $(function) =>是$(doucment).ready()的快捷键.当页面加载结束后才会执行function.$(function)可以调用多次,相当于绑定多个$(function)eg: $(function(){//document is ready})1.4 $(expr,context)=>在一定的范围(context)内根据搜索条件(expr)搜索出jQuery对像eg: 1. $(’span>p’) :找出所有span中的p结点.2.$(’input:radio’,document.forms[0])搜索出第一个表单中的radio2. $.extend(prop)向jquery命名空间中添加方法,用此方法可以方便的对jquery进行扩展$.extend({min: function(a, b) { return a < b ? a : b; },max: function(a, b) { return a > b ? a : b; }});alert($.min(3,6)); //显示3alert($.max(3,6));//显示63. $.noConflict() 取消$代替jQuery.例如:jQuery.noConflict(); // Do something with jQueryjQuery(”div p”).hide();// Do something with another library’s $()$(”content”).style.display = ‘none’;4. each(function) 对所以符合条件的结点做为参数调用function例如:$(”img”).each(function(i){ this.src=”test” + i + “.jpg”; });结果:<img/><img/>==》<img src=”test0.jpg”/><img src=”test1.jpg”/>5.eq(pos)取得对像element数组的第N+1个element例如:$(”p”).eq(1)<p>This is just a test.</p><p>So is this</p>=》<p>So is this</p>6. get() 取得所有的element数组例如: $(”img”).get();<img src="test1.jpg"/> <img src="test2.jpg"/> ===>[ <img src="test1.jpg"/> <img src="test2.jpg"/> ]get(num)可以取得指定的element例如:$("img").get(1)<img src="test1.jpg"/> <img src="test2.jpg"/> ===>[<img src="test2.jpg"/> ]7.index(subject) : 查找相应节点的位置,从0开始计数.如果没找到返回-1eg: <div id=”foobar”><b></b><span id=”foo”></span></div>$("*").index( $('#foobar')[0] ) =>0$("*").index( $('#foo')[0] ) => 2$("*").index( $('#bar')[0] )=> -18. length 返回节点的个数eg:<img src="test1.jpg"/> <img src="test2.jpg"/>$("img").length => 2同样的方法还有size()$("img").size() => 2;9. lt(pos) 删除一个节点eg:<p>This is just a test.</p><p>So is this</p>$("p").lt(1) ==>[ <p>This is just a test.</p> ]10. addClass 给一个element添加class可以添加多个eg: <p>Hello</p>$("p").addClass("selected")=>[ <p class="selected">Hello</p> ]$("p").addClass("selected highlight")=>[ <p class="selected highlight">Hello</p> ]11. attr(name) 取得element的指定属性值eg: <img src="test.jpg"/>$("img").attr("src") =>test.jpg;attr(key,value) 设置属性attr(key,function) 调用相应的方法处理后的返回值用来设置属性attr(properties) 批量的设置element的属性值eg: <img/>$("img").attr({ src: "test.jpg", alt: "Test Image" });==> <img src="test.jpg" alt="Test Image"/>$("img").attr("src","test.jpg")=><img src="test.jpg"/>以下两个方法等价:$("img").attr("title", "${this.src}")$("img").attr("title", function() { return this.src })==><img src="test.jpg" title="test.jpg" />12 html 取得element的html代码eg: <div><input/></div>$("div").html() => <input/>;html(val) 设置element的html代码eg: <div><input/></div>$("div").html("<b>new stuff</b>") ==><div><b>new stuff</b></div>;13 removeAttr(name) 删除属性eg: <input disabled=”disabled”/>$(”input”).removeAttr(”disabled”)=><input/>14 removeClass(class) 删除样式,当class是空时删除所有的样式,如果class为指定样式则删指定样式eg: <p class=”highlight selected first”>Hello</p>$(”p”).removeClass(”selected highlight”)=>[ <p class=”first”>Hello</p> ]$(”p”).removeClass() =>[ <p>Hello</p> ]15. text() 取得element中的内容text(val) 设置element内容text与html差不多,只是text会把<,>用html标识符替换eg: <p><b>Test</b> Paragraph.</p><p>Paraparagraph</p>$(”p”).text() =>T est Paragraph.Paraparagraph;<p>Test Paragraph.</p>$(”p”).text(”<b>Some</b> new text.”);==><p><b>Some</b> new text.</p>$(”p”).text(”<b>Some</b> new text.”, true) ==><p>Some new text.</p>16.toggleClass(class) 这是一个比较有用的方法,就是当element存在参数中的样式的时候取消,如果不存在就设置此样式eg:<p>Hello</p><p class="selected">Hello Again</p>$("p").toggleClass("selected")==>[ <p class="selected">Hello</p>, <p>Hello Again</p> ]17 val() 取得第一个element的vlaue值 val(val) 设置属性的值eg: <input type="text" value="some text"/>$("input").val() == >"some text";$("input").val("test")==><input type="text" value="test"/>;18 after(content)给相关的element从后面插入节点eg: <p>I would like to say: </p>$("p").after("<b>Hello</b>")==><p>I would like to say: </p><b>Hello</b><b>Hello</b><p>I would like to say: </p>$("p").after( $("b") )==><p>I would like to say: </p><b>Hello</b>;21 before(content)与after相反是插入到前面eg: <p>I would like to say: </p>$("p").after("<b>Hello</b>")==>><b>Hello</b><p>I would like to say: </p19 append(content)与上面不同的是append是添加把content做为子elementeg: <p>I would like to say: </p>$("p").append("<b>Hello</b>")=><p>I would like to say: <b>Hello</b></p>;eg: <p>I would like to say: </p><b>Hello</b>$("p").append( $("b") )==>;<p>I would like to say: <b>Hello</b></p>20 appendto(content)与append刚好相反<p>I would like to say: </p><div id="foo"></div>$("p").appendTo("#foo")==><div id="foo"><p>I would like to say: </p></div>;21 prepend(content) 添加到element里面的前部.与append 的方位不一样<p>I would like to say: </p>$("p").prepend("<b>Hello</b>")==><p><b>Hello</b>I would like to say: </p>;22 prependTo(content) 与prepend的添加对像相反.<p>I would like to say: </p><div id="foo"><b>Hello</b></div>$("p").prependTo("#foo") ==><div id="foo"><p>I would like to say: </p><b>Hello</b></div>;23 clone(deep) 克隆一个新的element.参数deep为flase里不包括子element<b>Hello</b><p>, how are you?</p>$("b").clone().prependTo("p")==><b>Hello</b><p><b>H ello</b>, how are you?</p>24.empty() 删除所有的内部节点<p>Hello, <span>Person</span> <a href="#">and person</a></p>$("p").empty()==>[ <p></p> ]25. insertAfter(content) 与after差不多.$(a).after(b) === $(b).insertAfter(a)26. insertBefore(content) 与 before差不多$(a).before(b) === $(b).insertBefore(a)27. remove(expt) 删除条件是expt的相应的element,当expt为空时.全部删除<p class="hello">Hello</p> how are <p>you?</p>$("p").remove(".hello")==>how are <p>you?</p>;28. wrap(html) 把节点插入到html生成的节点里面.要注意的是html节点中不能含有内容只能是节点的结构.如果想加的话只能在嵌入后再插入内容<p>Test Paragraph.</p>$("p").wrap("<div class='wrap'></div>")==><div class='wrap'><p>Test Paragraph.</p></div>注html也可以直接用一个element代替29 add(params) 在$所取到的节点数组中添加新的节点.参数可以是expr, html,elementeg: 1.<p>Hello</p><span>Hello Again</span>$(”p”).add(”span”)==>[ <p>Hello</p>, <span>Hello Again</span> ]2.<p>Hello</p>$(”p”).add(”<span>Again</span>”)==>[ <p>Hello</p>, <span>Again</span> ]3. <p>Hello</p><p><span id=”a”>Hello Again</span></p>$(”p”).add( document.getElementById(”a”) )===>[ <p>Hello</p>, <span id=”a”>Hello Again</spa n> ]30 children(expr)取得子节点,当expr为空时,取得所有的子节点eg<div><span>Hello</span><p class=”selected”>Hello Again</p><p>And Again</p></div>$(”div”).children()==>[><span>Hello</span><pclass=”selected”>Hello Again</p><p>AndAgain</p> ]$(”div”).children(”.selected”)==>[ <p class="selected">Hello Again</p> ]31 contains(str)找出字节点中包含有str的节点.str起到过滤做用eg: <p>This is just a test.</p><p>So is this</p>$("p").contains("test")==>[ <p>This is just a test.</p> ]32. filter(expression)过滤找出符合expression的节点eg:<p>Hello</p><p>Hello Again</p><p class="selected">And Again</p>$("p").filter(".selected")==>><p class="selected">And Again</p>$("p").filter(".selected, :first")==>[ <p>Hello</p>, <p class="selected">And Again</p> ]filter(filter_func)通过函数来选择是否过滤,filter_func返回true 表示过滤<p><ol><li>Hello</li></ol></p><p>How are you?</p> $("p").filter(function(index) { return $("ol", this).length == 0; })==>[ <p>How are you?</p> ]33. find(expr)从子节点找出符合expr的.与filter的区别是filter过滤掉$数组中的节点find过滤到的是子节点eg: <p><span>Hello</span>, how are you?</p>$("p").find("span")==>[ <span>Hello</span> ];34. is(expr) 判断是否符合条件,如果$数组的所有节点都不符合条件返回false,只要有一个符合条件就返回trueeg: <form><p><input type="checkbox" /></p></form>$("input[@type='checkbox']").parent().is("form")==>false$("input[@type='checkbox']").parent().is("p")==>true35 next(expr) 取得最近节点最近那个节点.expr为空时取得所有节点eg:1.<p>Hello</p><p>Hello Again</p><div><span>And Again</span></div>$("p").next()==>[ <p>Hello Again</p>, <div><span>And Again</span></div> ]2.<p>Hello</p><p class="selected">Hello Again</p><div><span>And Again</span></div>$("p").next(".selected")==>[ <p class="selected">Hello Again</p> ]36. not(el),not(expr),not(elems)与add相反,删除符合条件的节点.eg:1. <p>Hello</p><p id="selected">Hello Again</p>$("p").not( $("#selected")[0] )==>[ <p>Hello</p> ]$("p").not("#selected")==>[ <p>Hello</p> ]2.<div><p>Hello</p><p class="selected">Hello Again</p></div>$("p").not( $("div p.selected") )==>[ <p>Hello</p> ]37 parent(expr) 取得父节点eg:1.<html><body><div><p><span>Hello</span></p>< span>HelloAgain</span></div></body></html>$("span").parents()==>[ <body>...</body>, <div>...</div>, <p><span>Hello</span></p> ]2.<html><body><div><p><span>Hello</span></p><sp an>Hello Again</span></div></body></html>$("span").parents("p")==>[ <p><span>Hello</span></p> ]38 prev(expr) 与next相反,next取得是与节点相邻后面的.prev 取得相邻前面的eg: 1.<div><span>Hello</span></div><p class="selected">Hello Again</p><p>And Again</p> $("p").prev(".selected")==>[ <div><span>Hello</span></ div> ]2.<p>Hello</p><div><span>HelloAgain</span></div><p>And Again</p>$("p").prev()==>[ <div><span>Hello Again</span></div> ]39 siblings(expr) 取得相邻两边的节点是.next,与prev的结合体jquery与dom相关的操作先讲到这里,下回接着讲CSS相关操作40 1/. CSS(name)读取样式属性值eg:<p style=”color:red;”>Test Paragraph.</p>$(”p”).css(”color”)==>”red”;2/css(properties)设置styleeg:<p>T est Paragraph.</p>$("p").css({ color: "red", background: "blue" })==><p style="color:red; background:blue;">Test Paragraph.</p>;3/css(key, value)设置单个样式属性,如果设置的值是数字的话,会被自动转化为像素单位eg : <p>Test Paragraph.</p>$("p").css("color","red")==><p style="color:red;">Test Paragraph.</p>;$("p").css("left",30)==><p style="left:30px;">Test Paragraph.</p>;41 1/height()取得当前匹配节点数组中的第一个节点的高的值eg: <p>This is just a test.</p>$("p").height() ==>300;2/ height(val) 设置所有匹配的节点的高,如果val的单位不是ex ,%,那么单位自动设为pxeg: <p>This is just a test.</p>$("p").height(20)==><p style="height:20px;">This is just a test.</p>;42 width() 设置宽度,width(val)设置高度.用法与height一样以上是基本的CSS的js用法,下面主要记录jQuery的一些功能函数43 $.browser 用于判断浏览器的分别为safari,opera, msie, mozilla.这些方法要等DOM ready后才能使用eg: if($.browser.safari) {$( function() { alert("this is safari!"); } ); }44. $.each(obj, fn) 这个方法与$().each()不一样,前者可以迭代任务数组与对像,后者只能迭代jQuery对象$.each( [0,1,2], function(i, n){ alert( "Item #" + i + ": " + n ); });45 $.extend(target, prop1, propN)继承多个对象.target被扩展的对象.prop1,第一个父对象,propN其它被继承的对象eg: 1. var settings = { validate: false, limit: 5, name: "foo" };var options = { validate: true, name: "bar" };jQuery.extend(settings, options);====>settings == { validate: true, limit: 5, name: "bar" }2.var defaults = { validate: false, limit: 5, name: "foo" };var options = { validate: true, name: "bar" };var settings = jQuery.extend({}, defaults, options);===>settings == { validate: true, limit: 5, name: "bar" }46 $.grep(array, fn, inv)用fn过滤array,当fn返回true时array 元素保留在数组中eg : $.grep( [0,1,2], function(i){ return i > 0; });==>[1, 2]47 $.map(array, fn)通过fn修改array中的值当函数返回值为null里,array元素将被删除,当返回是数组时,返回的数组将与原数组合并eg: 1.$.map( [0,1,2], function(i){ return i + 4; });==>[4, 5, 6]2.$.map( [0,1,2], function(i){ return i > 0 ? i + 1 : null; });==>[2, 3]3.$.map( [0,1,2], function(i){ return [ i, i + 1 ]; });==>[0, 1, 1, 2, 2, 3]48. $.merge(first, second)两个数组进行合并,删除重复的值$.merge( [0,1,2], [2,3,4] )==>[0,1,2,3,4]$.merge( [3,2,1], [4,3,2] )==>[3,2,1,4]49 $.trim(str)去除字符串两端的空格,一个十分熟悉常用的方法$.trim(" hello, how are you? ")==>"hello, how are you?";主要记录jQuery事件响应的处理50. bind(type, data, fn)对所有选定的element判断事件,type是事件类型,data是参数,fn是事处理方法.eg:1. $(”p”).bind(”click”, function(){ alert( $(this).text() ); });2. function handler(event) { alert(event.data.foo); }$(”p”).bind(”click”, {foo: “bar”}, handler)==>alert(”bar”)51. blur() 触发blur方法,blur(fn)设置blur函数eg: <p>Hello</p>$(”p”).blur( function() { alert(”Hello”); } );==><p onblur=”alert(’Hello’);”>Hello</p>52. change(fn)设置onchange事件的方法eg:<p>Hello</p>$(”p”).change( function() { alert(”Hello”); } );==><p onchange=”alert(’Hello’);”>Hello</p>53 click()触发onclick事件, click(fn)设置onclick方法54. dblclick(fn)设置ondblclick方法55.error(fn)设置error方法56 focus()触发onfocus,focus(fn)设置focus方法eg:<p>Hello</p>$(”p”).focus( function() { alert(”Hello”); } );==><p onfocus=”alert(’Hello’);”>Hello</p>57 hover(over, out) 设置mouse移入以及mouse移出时所触发的事件.eg: $("p").hover(function(){$(this).addClass("over");},function(){$(this).addClass("out");});58 keydown(fn),keypress(fn),keyup(fn),按键盘相关的操作分别对应onkeydown,onkeypress,onkeyup.59mousedown(fn),mousemove(fn),mouseout(fn),mouseover(fn),m ouseup(fn)这些是mouse相关的操作分别对应onmousedown,onmousemove,onmouseout,onmouseover,onmo useup.60 load 当element load事件发生时触发eg <p>Hello</p>$("p").load( function() { alert("Hello"); } );==><p onload="alert('Hello');">Hello</p>61.one(type, data, fn)与bind差不多,最大的区别是前者只运行一次后便不再响应.如果运行后不想继续运行默认的方法只要fn中返回值return false就可以了.eg: <p>Hello</p>$("p").one("click",function(){ alert( $(this).text() ); });==>alert("Hello")62.ready(fn)当dom 结构载入完毕的时候.用此方法时,请不要在onload方法里面写代码.不然就不会触发ready事件eg .1.$(document).ready(function(){ Your code here... });2.jQuery(function($) {// Your code using failsafe $ alias here...});63.resize 设置onresize方法.当大小改变时触发eg: <p>Hello</p>$("p").resize( function() { alert("Hello"); } );<p onresize="alert('Hello');">Hello</p>64 scroll(fn) 设置onscroll方法65.select()触发onselect方法.select(fn)设置select方法66. submit()提交表单,submit(fn)设置submit方法.eg: $("#myform").submit( function() {return $("input", this).val().length > 0; } );<form id="myform"><input /></form>67 toggle(even, odd),even当偶数单击时运行,odd当奇数单击时运行.用unbind(’click’)删除eg: $("p").toggle(function(){$(this).addClass("selected");},function(){$(this).removeClass("selected");});68 trigger(type)触发相应的type方法eg: <p click="alert('hello')">Hello</p>$("p").trigger("click")==>alert('hello')69 unbind(type, fn)与bind相反,1.unbind()删除所有的绑定.eg:<p onclick="alert('Hello');">Hello</p>$("p").unbind()==>[ <p>Hello</p> ]2.unbind(type)删除指定的绑定eg:<p onclick="alert('Hello');">Hello</p>$("p").unbind( "click" )==>[ <p>Hello</p> ]3.unbind(type, fn)删除指定type的指定fneg:<p onclick="alert('Hello');">Hello</p>$("p").unbind( "click", function() { alert("Hello"); } )==>[ <p>Hello</p> ]70 unload(fn)当页面unload的时候触发方法eg: <p>Hello</p>$("p").unload( function() { alert("Hello"); } );==><p onunload="alert('Hello');">Hello</p>主要关于如何用jQuery处理特效(70-76)71. animate(params, speed, easing, callback)动画特效.params:是动画的设置,用来表示动画的展现以及结束,speed:动画的速率可以是(”slow”, “normal”, or “fast”)也可以是毫秒数.eg: 1000easing:默认是’linear’,如想用其它参数,就要添加jQuery的特效插件.callback: 当动画完成时的调用的函数.eg:1. $(”p”).animate({ height: ‘toggle’, opacity: ‘toggle’ }, “slow”);2. $(”p”).animate({ left: 50, opacity: ’show’ }, 500);3. $(”p”).animate({ opacity: ’show’}, “slow”, “easein”);72. fadeIn(speed, callback),fadeOut(speed, callback),fadeTo(speed, opacity, callback)淡入,淡出效果,speed表示速度,可以用”slow,normal,fast”代替,也可以直接写毫秒数. callback表示淡入,淡出后的调用的函数.fadeTo表示淡入到某个透明度。
一、jQuery 教程jQuery 是一个JavaScript 库。
jQuery 极大地简化了JavaScript 编程。
jQuery 很容易学习。
每一章中用到的实例<html><head><script type="text/javascript" src="jquery.js"></script> <script type="text/javascript">$(document).ready(function(){$("p").click(function(){$(this).hide();});});</script></head><body><p>If you click on me, I will disappear.</p></body></html>亲自试一试代码:<!DOCTYPE html><html><head><script src="/jquery/jquery-1.11.1.min.js"></script><script>$(document).ready(function(){$("p").click(function(){$(this).hide();});});</script></head><body><p>如果您点击我,我会消失。
</p><p>点击我,我会消失。
</p><p>也要点击我哦。
</p></body></html>通过点击"TIY" 按钮来看看它是如何运行的。
锋利的jQuery学习笔记一、认识JQuery页面加载事件(可以写多个ready())$(document).ready(function(){alert(“hello world”);})链式操作:JQuery允许你在一句代码中操做任何与其相关联的元素,包括其子元素、父元素等$(“#myDiv”).addClass(“css1″).children(“a”).removeClass(“css2″);//选择名称为myDiv的元素,为其自身添加css1的样式,然后再选择其所有子元素a,为其移除css2样式JQuery中获得一个对象的所有子元素内容$(“#myDiv”).html()JQuery中的变量与 DOM中的变量var $myVar = “”;var myVar = “”;DOM对象转换成 JQuery对象var obj = documnet.getElementById(“myDiv”);var $obj = $(obj);JQuery对象转换成 DOM对象var $obj = $(“#myDiv”);var obj = $obj.get(0); //或者var obj = $obj[0];释放JQuery对$符号的控制权JQuery.noConflict();二、JQuery选择器JQuery完善的处理机制ocument.getElementById(“test”).style.color = “red”; //如果test不存在,则页面出现异常$(“#test”).css(“color”,”red”); //哪怕页面没有名称为test的元素,也不会报错。
它是一个JQuery对象判断页面是否选择的对象if( $(“.class”).length > 0 ){// todo something}基本选择器$(“#myDiv”)//根据给定的ID选择匹配的元素,返回:单个元素$(“.myClass”) //根据给定的样式名称选择匹配的元素,返回:集合元素$(“div”) //根据给定的元素名称选择匹配的元素,返回:集合元素$(“#myDiv,div.myClass,span”) //根据给定的规则选择匹配的元素,返回:集合元素$(“*”) //选择页面所有元素,返回:集合元素层次选择器$(“div span”) //选择所有DIV元素下的所有SPAN元素(所有后代元素),返回:集合元素$(“div>span”) //选择所有DIV元素下的SPAN子元素(仅子元素),返回:集合元素$(“.myClass+div”) //选择样式名称为myClass的下一个DIV元素,返回:集合元素$(“.myClass+div”) //等价于$(“.myClass”).next(“div”);$(“.myClass~div”) //选择样式名称为myClass之后的所有DIV元素,返回:集合元素$(“.myClass~div”) //等价于$(“.myClass”).nextAll();$(“.myClass”).siblings(“div”)//选择样式名称为myClass的元素的所有同辈DIV元素(无论前后),返回集合元素过滤选择器(index从0开始)$(“div:first”) //选择所有DIV元素下的第一个DIV元素,返回:单个元素$(“div:last”)//选择所有DIV元素下的最后一个DIV元素,返回:单个元素$(“div:not(.myClass)”) //选择所有样式不包括myClass的DIV元素,返回:集合元素$(“div:even”) //选择所有索引是偶数的DIV元素,返回:集合元素$(“div:odd”) //选择所有索引是奇数的DIV元素,返回:集合元素$(“div:eq(index)”) //选择所有索引等于index的DIV元素,返回:集合元素$(“div:gt(index)”) //选择所有索引大于index的DIV元素,返回:集合元素$(“div:lt(index)”) //选择所有索引小于index的DIV元素,返回:集合元素$(“:header”) //选择所有标题元素(h1,h2,h3),返回:集合元素$(“div:animated”) //选择所有正在执行去画的DIV元素,返回:集合元素子元素过滤选择器(index从1开始)$(“:nth-child(index/even/odd)”) //选择每个父元素下的第index/偶数/奇数个子元素,返回:集合元素$(“:first-child”) //选择每个父元素下的第一个子元素,返回:集合元素$(“:last-child”) //选择每个父元素下的最后一个子元素,返回:集合元素$(“ul li:only-child”) //在UL元素中选择只有一个LI元素的子元素,返回:集合元素内容过滤选择器$(“:contains(text)”) //选择所有内容包含text的元素,返回:集合元素$(“div:empty”) //选择所有内容为空的DIV元素,返回:集合元素$(“div:has(span)”)//选择所有含有SPAN子元素的DIV元素,返回:集合元素$(“div:parent”) //选择所有含有子元素的DIV元素,返回:集合元素可见性选择器$(“:hidden”) //选择所有不可见的元素(type=”hidden”style=”display:none” style=”visibility:none”),返回:集合元素$(“:visible”) //选择所有可见的元素,返回:集合元素属性过滤选择器$(“[id]“) //选择所有含有id属性的元素,返回:集合元素$(“[class=myClass]”) //选择所有class属性值是myClass的元素,返回:集合元素$(“[class!=myClass]”) //选择所有class属性值不是myClass的元素,返回:集合元素$(“[alt^=begin]”) //选择所有alt属性值以begin开始的元素,返回:集合元素$(“[alt^=end]”) //选择所有alt属性值以end结束的元素,返回:集合元素$(“[alt*=some]”)//选择所有alt属性值含有some的元素,返回:集合元素$(“div[id][class=myClass]”) //选择所有含有id属性的并且class属性值是myClass的元素,返回:集合元素表单对象属性选择器$(“#myForm:enabled”) //选择ID属性为myForm的表单的所有可用元素,返回:集合元素$(“#myForm:disabled”) //选择ID属性为myForm的表单的所有不可用元素,返回:集合元素$(“#myForm:checked”) //选择ID属性为myForm的表单的所有所有被选中的元素,返回:集合元素$(“#myForm:selected”) //选择ID属性为myForm的表单的所有所有被选中的元素,返回:集合元素表单选择器$(“:input”) //选择所有<input> <select> <button> <textarea>元素,返回:集合元素$(“:text”) //选择所有单行文本框元素,返回:集合元素$(“:password”) //选择所有密码框元素,返回:集合元素$(“:radio”) //选择所有单选框元素,返回:集合元素$(“:checkbox”) //选择所有复选框元素,返回:集合元素$(“:submit”) //选择所有提交按钮元素,返回:集合元素$(“:image”) //选择所有图片按钮元素,返回:集合元素$(“:reset”) //选择所有重置按钮元素,返回:集合元素$(“:button”) //选择所有按钮元素,返回:集合元素$(“:file”) //选择所有上传域元素,返回:集合元素$(“:hidden”) //选择所有不可见域元素,返回:集合元素$(“:text”) //选择所有单选文本框元素,返回:集合元素三、JQuery中的DOM操作查找元素节点var str = $(“#myDiv”).text(); //<div id=”myDiv”title=”hello”>123</div>alert(str); //结果:123查找属性节点var str = $(“#myDiv”).attr(“title”); //<div id=”myDiv”title=”hello”>123</div>alert(str); //结果:hello创建元素节点var $li1 = $(“<span></span>”); //传入元素标记,自动包装并创建第一个li元素对象va r $li2 = $(“<span></span>”); //第二个,创建时需要遵循XHTML规则(闭合、小写)$(“#myDiv”).append($li1); //往id为myDiv的元素中添加一个元素$(“#myDiv”).append($li2); //结果:<divid=”myDiv”><span></span><span></span>< ;/div>$(“#myDIv”).append($li1).append($li2); //客串:传说中的链式写法,省一行代码 ^_^创建文本节点var $li1 = $(“<span>first</span>”);var $li2 = $(“<span>second</span>”);$(“#myDIv”).append($li1).append($li2);//结果:<divid=”myDiv”><span>first</span><span>sec ond</ span></div>创建属性节点var $li1 = $(“<span title=”111″>first</span>”);var $li2 = $(“<span title=”222″>second</span>”); $(“#myDIv”).append($li1).append($li2);//结果:<div id=”myDiv”><spantitle=”111″>first</span><spantitle=”222″>second</span></div>插入节点$(“#myDiv”).append(“<span></span>”); //往id为myDiv 的元素插入span元素$(“<span></span>”).appendTo(“#myDiv”); //倒过来,将span元素插入到id为myDiv的元素$(“#myDiv”).prepend(“<span></span>”); //往id为myDiv 的元素内最前面插入span元素$(“<span></span>”).prependTo(“#myDiv”); //倒过来,将span元素插入到id为myDiv的元素内的最前面$(“#myDiv”).after(“<span></span>”); //往id为myDiv的元素后面插入span元素(同级,不是子元素)$(“<span></span>”).insertAfter(“#myDiv”); //倒过来,将span元素插入到id为myDiv的元素后面(同级,不是子元素)$(“#myDiv”).before(“<span></span>”); //往id为myDiv 的元素前面插入span元素(同级,不是子元素)$(“<span></span>”).insertBefore(“#myDiv”); //倒过来,将span元素插入到id为myDiv的元素前面(同级,不是子元素)删除节点$(“#myDiv”).remove();//将id为myDiv的元素移除清空节点$(“#myDiv”).remove(“span”); //将id为myDiv的元素内的所有span元素移除复制节点$(“#myDiv span”).click( function(){//点击id为myDiv的元素内的span 元素,触发click事件$(this).clone().appendTo(“#myDiv”); //将span元素克隆,然后再添加到id为myDiv的元素内$(this).clone(true).appendTo(“#myDiv”); //如果clone传入true参数,表示同时复制事件})替换节点$(“p”).replaceWith(“<strong>您好</strong>”); //将所有p元素替换成后者 <p>您好</p> –> <strong>您好</strong>$(“<strong>您好</strong>”).replaceAll(“p”); //倒过来写,同上包裹节点$(“strong”).wrap(“<b></b>”); //用b元素把所有strong 元素单独包裹起来 <b><strong>您好</strong></b><b><strong>您好</strong></b>$(“strong”).wrapAll(“<b></b>”); //用b元素把所有strong元素全部包裹起来 <b><strong>您好</strong><strong>您好</strong></b> $(“strong”).wrapInner(“<b></b>”); //把b元素包裹在strong元素内 <strong><b>您好</b></strong>属性操作var txt = $(“#myDiv”).arrt(“title”); //获取id为myDiv的元素的title 属性$(“#myDiv”).attr(“title”,”我是标题内容”); //设置id为myDiv的元素的title属性的值$(“#myDiv”).attr({“title”:”我是标题内容”, “alt”:”我还是标题”); //一次性设置多个属性的值$(“#myDiv”).removeArrt(“alt”); //移除id为myDiv的元素的title属性样式操作var txt = $(“#myDiv”).arrt(“class”); //获取id为myDiv的元素的样式$(“#myDiv”).attr(“class”,”myClass”); //设置id为myDiv的元素的样式$(“#myDiv”).addClass(“other”); //在id为myDiv的元素中追加样式$(“#myDiv”).removeClass(“other”); //在id为myDiv的元素中移除other 样式$(“#myDiv”).removeClass(“myClass other”); //在id为myDiv的元素中移除myClass和other多个样式$(“#myDiv”).removeClass(); //在id为myDiv的元素中移除所有样式$(“#myDiv”).toggleClass(“other”); //切换样式,在有other样式和没other样式之间切换$(“#myDiv”).hasClass(“other”); //判断是否有other样式设置和获取HTML、文本和值alert( $(“#myDiv”).html() ); //获取id为myDiv的元素的HTML代码(相当于innerHTML)$(“#myDiv”).html(“<span>hello</span>”); //设置id为myDiv的元素的HTML代码alert( $(“#myDiv”).text() ); //获取id为myDiv的元素的HTML代码(相当于innerText)$(“#myDiv”).text(“hello”); //设置id为myDiv的元素的HTML代码alert( $(“#myInput”).val() ); //获取id为myDiv的元素的value值(支持文本框、下拉框、单选框、复选框等)$(“#myInput”).val(“hello”); //设置id为myDiv的元素的value值(下拉框、单选框、复选框带有选中效果)遍历节点var $cList = $(“#myDiv”).children(); //获取id为myDiv的元素的子元素(只考虑子元素,不考虑后代元素)var $sNext = $(“#myDiv”).next(); //获取id为myDiv的元素的下一个同辈元素var $sPrev = $(“#myDiv”).prev(); //获取id为myDiv的元素的上一个同辈元素var $sSibl = $(“#myDiv”).siblings(); //获取id为myDiv的元素的所有同辈元素var $pClos = $(“#myDiv”).closest(“span”); //获取id为myDiv的元素本身开始,最接近的span元素(向上查找)CSS-DOM操作$(“#myDiv”).css(“color”); //获取id为myDiv的元素的color样式的值$(“#myDiv”).css(“color”, “blue”); //设置id为myDiv的元素的color 样式的值$(“#myDiv”).css({“color”:”blue”, “fontSize”:”12px”}); //设置id为myDiv的元素的color样式的值(多个)$(“#myDiv”).css(“opacity”, “0.5″); //设置id为myDiv的元素的透明度(兼容浏览器)$(“#myDiv”).css(“height”); //获取id为myDiv的元素的高度(单位:px,兼容浏览器)$(“#myDiv”).height(); //同上(实际高度)$(“#myDiv”).css(“width”); //获取id为myDiv的元素的宽度(单位:px,兼容浏览器)$(“#myDiv”).width(); //同上(实际宽度)var offset = $(“#myDiv”).offset(); //获取id为myDiv的元素在当前窗口的相对偏移量alert( offset.top + “|” + offset.left );var offset = $(“#myDiv”).position(); //获取id为myDiv的元素相对于最近一个position设置为relative或absolute的父元素的相对偏移量alert( offset.top + “|” + off set.left );$(“#txtArea”).scrollTop();//获取id为txtArea的元素滚动条距离顶端的距离$(“#txtArea”).scrollLeft(); //获取id为txtArea的元素滚动条距离左侧的距离$(“#txtArea”).scrollTop(100); //设置id为txtArea的元素滚动条距离顶端的距离$(“#txtArea”).scrollLeft(100); //设置id为txtArea的元素滚动条距离左侧的距离四、JQuery中的事件和动画加载DOM$(window).load() 等价于 window.onload 事件$(document).ready() 相当于window.onload事件,但有些区别:(1)执行时机:window.onload 是在网页中所有元素(包括元素的所有关联文件)完全加载后才执行$(document).ready() 是在DOM完全就绪时就可以被调用,此时,并不意味着这些元素关系的文件都已经下载完毕(2)多次使用:可以在同一个页面注册多个$(document).ready()事件(3)简写方式:可以缩写成 $(function(){ }) 或 $().ready()事件绑定当文档装载完成后,可以通过bind()方法,为特定的元素进行事件的绑定,可重复多次使用bind( type, [data, ] fn );type:指事件的类型:blur(失去焦点)、focus(获得焦点)load(加载完成)、unload(销毁完成)resize(调整元素大小)、scroll(滚动元素)click(单击元素事件)、dbclick(双击元素事件)mousedown(按下鼠标)、mouseup(松开鼠标)mousemove(鼠标移过)、mouseover(鼠标移入)、mouseout(鼠标移出)mouseenter(鼠标进入)、mouseleave(鼠标离开)change(值改变)、select(下拉框索引改变)、submit(提交按钮)keydown(键盘按下)、keyup(键盘松开)、keypress(键盘单击)error(异常)data:指事件传递的属性值,event.data 额外传递给对象事件的值fn:指绑定的处理函数,在此函数体内,$(this)指携带相应行为的DOM元素合并事件hover(enter,leave):鼠标移入执行enter、移出事件执行leave$(“#myDiv”).hover( function(){$(this).css(“border”, “1px solid black”);0}, function(){$(this).css(“border”, “none”);});toggle(fn1,fn2,…fnN):鼠标每点击一次,执行一个函数,直到最后一个后重复$(“#myDiv”).toggle( function(){$(this).css(“border”, “1px solid black”);0}, function(){$(this).css(“border”, “none”);});事件冒泡下面的例子,BODY元素下有DIV元素,DIV元素下有SPAN元素,分别将三种元素都注册click事件。
一、jQuery基础1.1 jQuery的特点1)jQuery是一种框架,对于浏览器的兼容问题,95%不用再去考虑了。
2)jQuery利用选择器(借鉴了CSS选择器的语法)查找要操作的节点(DOM对象),然后将这些节点封装成一个jQuery对象(封装的目的有两个:①是为了兼容不同的浏览器。
②也为了简化代码)。
通过调用jQuery对象的方法或者属性来实现对底层的DOM对象的操作。
3)jQuery特点简单概括就是:选择器+ 调方法。
1.2 jQuery编程的步骤step1:引入jQuery框架(下载),min为去掉所有格式的压缩版<script language="javascript" src="js/jquery-1.4.1.min.js"></script>step2:使用选择器查找要操作的节点(该节点会被封装成一个jQuery对象,并返回)var $obj=$('#di');//ID选择器,查找的节点ID为d1step3:调用jQuery对象的方法或者属性$obj.css('font-size','60px');//调用jQuery的css()方法◆注意事项:jQuery是一个大的匿名函数,且内部有很多函数(类似Java中的内部类),它的大部分函数返回对象都是jQuery对象(它自己),所以可以继续“.”,例如:function f1(){var $obj=$('#d1');//为了强调返回的是jQuery对象,命名习惯用$开头来声明变量$obj.css('font-size','60px').css('font-style','italic'); } 1.3 jQuery对象与DOM对象如何相互转换1)dom对象如何转化为jQuery对象使用函数:$(dom对象)即可,例如:function f2(){var obj=document.getElementById('d1');var $obj=$(obj);//将dom节点封装成jQuery对象$obj.html('hello java'); } 2)jQuery对象如何转化为dom对象方式一:$obj.get(0); 方式二:$obj.get()[0];function f3(){var $obj=$('#d1'); //方式一:var obj=$obj.get(0);var obj=$obj.get()[0];//方式二obj.innerHTML='hello perl'; } 1.4如何同时使用prototype和jQuerystep1:先导入prototype.js,再导入jQuery.jsstep2:将jQuery的$函数换一个名字:var $a=jQuery.noConflict();//注意大小写◆注意事项:函数名就是一个变量,指向函数对象,例如:<script language="javascript" src="js/prototype-1.6.0.3.js"></script><script language="javascript" src="js/jquery-1.4.3.js"></script>function f1(){//无效var obj=$('d1'); }//无效是因为jQuery是后引入的,所以prototype被jQuery替换function f1(){//为了避免冲突,可以将jQuery的$函数换一个名字$avar $a=jQuery.noConflict(); var obj=$('d1');obj.innerHTML='hello prototype'; $a('#d1').html('hello jQuery'); } 1.5 EL表达式和jQuery函数的区别1)${}:EL表达式,在服务器端运行(JSTL标签库也在服务器端运行,EL和JSTL标签库本质是Java代码)。
第一章一、$(document).ready(function(){//do something});和window.onload的区别1.前者同一页面可以使用多次,后者出现多次只有最后一次能正确显示2.前者在DOM模型加载完成后就开始执行,后台在所有元素(包括图片)加载完成后执行3.前者可以简化为$(function(){//do something});后者没有简写形式。
二、jQuery比较常使用的是链式操作,比如一个书目导航条:$(function(){$(“ul”).click(function(){$(this).addClass(“current”).children(“li”).slideDown().end().sublings().removeClass(“current”).children(“li”).slideUp();})})对于同一元素不超过3个操作的,一般写同一行,如果操作过多,可以将类似的操纵写成一行,便于阅读。
三、jQuery对象和DOM对象的转换1.jQuery转化为DOM对象Var $variable = $(“tr”); //jQuery objectVar variable = $variable[0]; //DOM objectThe transpartent method.DomObject = jQueryObject[index] or = jQueryObject.get(index).2.DOM Object To jQuery ObjectVar variable = getElementsByTagName(“tr”); //DOM objectVar $variable = $(variable) // jQuery object;The transpartent method.jQueryObject = $(DomObject)四、jQuery开发工具1.Dreamweaver 可以安装插件提示jQuery 插件名称:jQuery_API.mxp2.Aptana 功能非常强大的、开源、专注javascript和Ajax开发IDE;3.Visual Studio 2008。
JQuery等价于$$(document).ready(function(){});简写==$(function(){});返回值都为[object Object]容错,jQ发生错误不报错1,jq选择器1>基本选择器$(“#idName”)------通过id找元素$(“.className” )------通过class找元素$(“tagName”)-------通过标签找元素$(“*”)---------匹配所有的元素$(“li *”)----li下的全部一般用于局部环境内$(“selector1,selector2”)---群组匹配元素$(“box.div”)-----限定必须是box元素的div2,层级选择器$(“a b”)-----匹配a的后代中所有b元素$(“a>b”)----匹配a中子代b元素(只找儿子,不找孙子)$(“a+b”)----匹配紧邻的一个兄弟b元素(紧邻,一个)$(“a~b”)----匹配a之后的所有兄弟b元素(之后所有)3,过滤选择器1>基本选择器a>特定位置的过滤$(“li:first”)--- --匹配第一个li元素$(“li:last”) ---匹配找到的li中最后一个li元素$(“li:eq(index)”)---匹配找到的li中索引为index的li。
(index从零开始)b>指定范围的过滤$(“li:lt(index)”) --匹配index之前的所有li(不包含index位置的li);$(“li:gt(index)”)---匹配index之后的所有li(不包含index位置的li)$(“li:not(selector)”)---匹配除了not的li内元素$(“li:odd”)----匹配偶数行(索引为奇数)的li$(“li:even”)----匹配奇数行(索引为偶数)的li2>属性过滤$(“[标签属性]”)-----匹配有该属性的俄元素$(“[标签属性=值]”)---匹配属性=指定的元素$(“[标签属性^=value]”)$(“[标签属性$=value]”)$(“[标签属性!=value]”)3>子元素选择器$(“li:first”)------将所有匹配到的元素中只选第一个(返回第一个元素)$(“li:first-child”)----匹配每个li的父元素的第一个孩子(可返回多个元素)$(“li:last”)和(“li:last-child”)用法与以上类似$(“li:only-child”)------匹配li的父级只有一个孩子的li元素val=$(“#id”).val()---获取#id 的文本内容$("#btn").click(function(){var val=$("#txt").val();$("a:contains('"+val+"')").css("background","red");})4>内容过滤$(“li:contexts(text)”)--匹配内容中包含了text的文本的li$(“li:has(selector)”)---匹配内容中包含了selector元素的li$(“li:empty”)-----匹配内容为空的li元素$(“li:parent”)----匹配以li为父元素的DOM节点5>可见和隐藏选择器$(“div:hidden”)----匹配div中设置了display为none的元素,通过其他方式不可见的元素匹配不到;$(“div:visible”)---匹配div中没有设置display为none的元素,只认display设置不为none的元素备注:此选择器只以display设置的结果为准4,表单选择器$(“:input”) ------所有的表单中的控件:input button select$(“:text”)-------文本输入框---所有的input标签type属性值之前加冒号--表示相应的input元素$(“:disable”)---所有表单控件中设置了disable属性的元素$(“:enable”)----所有的表单控件中没有设置disable属性的元素$(“:checked”)---匹配被选中的单选按钮或者复选框$(“:selected”)---匹配被选中的option元素2,获取文本text( )------只获取到文本内容html( )-----获取包含标签在内的所有内容val( ) -----获取表单控件的文本设置内容text(“内容”)------设置内容,不解析标签html( “内容”)-----获取包含标签在内的所有内容val( “内容”) -----获取表单控件的文本.val([“check”,”radio”])----通过数组传递设置选定状态3,获取和设置元素的特性attr(“标签属性”)------获取该属性attr(“标签属性“,”属性值)-----设置该属性设置多个属性:attr({ 属性:属性值,属性:属性值});备注:多个属性设置之间用逗号分隔,最后一个无任何符号删除属性:removeAttr(“标签属性”)4,获取和设置DOM对象的属性property获取:prop( “属性”)设置:Prop(“属性””属性值”)备注:互补与attr( ),, 更适应结果为boolth的类型,5,attrbute和property区别1,区别:表示的意思不一样attrbute特性--所有设置的标签属性都存在attrbute类关联数组中获取:attrbute[ i ] 或者attrbute[“特性名”]property 属性标签有的特性,并已经设置了,可以通过property的方式获取获取:对象.属性名设置:如果对象没有该属性,可以通过对象.属性名=属性值jq:通过prop()方式设置的属性,通过attr()的方式获取不到对象没有的,通过attr()方式设置的,通过prop()的方式获取不到;联系:DOM元素有该特性,并且已经设置了,两种方式度可以获取到补充:通过attr( )获取不到的或设置不了的特殊属性,我们可以通过prop( )获取和设置例如:表单控件的checked属性;6,each( )----遍历每一个匹配到的元素使用语法:each(function(i,ele){ 执行内容});i-----表示每一个元素的索引Ele-----表示匹配到的每一个元素$(Ele)---将获取到的DOM元素转换成jq对象----用jq的API数组与遍历结合使用var arr=["#000","#0f0","#00f","#0ff","#f0f"];$(".warp").each(function(i){$(".warp").eq(i).css("backgroundColor",arr[i]);}); 这里不能使用this7,修改css属性的方法:attr(“class”,”类名”)addClass(“类名”)--------追加样式removeClass(“类名”)-----删除指定的类名removeclass( )------删除所有的类名toggleClass(“类名”)-------切换类名(在有和没有该类名之间切换)hasClasscss(“css属性”)--------获取一个css属性的值css(“css属性”,”属性值”)---设置一个csss属性css({属性:“属性值”,属性:“属性值”});8,获取索引:index( )-----在同辈中找索引index(“selector”)---在指定的同类(同辈)中找索引9,js对象和jq对象相互转换js-----jq 适用$( )工厂函数------$( js对象)jq----js $(“”)[index] 或者$(“”).get( index )转换之后的对象可以用彼此的API10,节点的遍历children( )/children( selector )----子代/子代中某个find( selector )-------在子孙后代中查找指定元素next( )/next( selector )------之后紧跟的一个兄弟元素/筛选某个紧邻的元素nextALL( )/nextAll( selector )----之后所有的兄弟元素prev( )/prev( selector )prevALL/prevALL( selector )siblings( )-----所有兄弟元素不包含自身parent( )------父元素输出---遍历到的内容console.log--只能输出一个,,用each( )11,创建元素$() 工厂函数创建var tr=$("<tr></tr>");$("#oDiv table").append(tr);添加元素父.append(子)----------子元素插入在父元素内容的后面父.preppend(子)--------子元素插入在父元素的内容的前面父.before(子)-----------子元素插入在父元素容器的前面父.after(子)--------------子元素插入在父元素容器的后面补充:反方向操作子.apppendTo(父)preppendTo(父)insertBefore(父)insertAfter(父)12, 替换被替换元素.replaceWith(替换的内容);替换的内容.replaceAll(被替换元素);13,删除要删除的元素.remove();-----------------将匹配到的元素全部删除要删除的元素.remove(“selector”)-----匹配到的元素筛选后再删除14,复制jq对象.clone()------------------将匹配到的jq对象复制如果:jq对象使用嵌入的绑定事件,连同事件一起被复制如果:jq对象使用的分离式绑定事件,绑定的事件不会被复制如果想将分离式绑定的事件一起被复制:jq对象.clone(true);备注:clone()紧紧是复制,并没有挂在DOM树上15,页面加载事件全写:jQuery(document).ready(function(){js语句})简写:$(function(){js语句})16,js的load事件和jq的ready事件的区别js中多个load事件只执行最后一个,jq的多个ready事件都会执行执行时机不同:js的load事件是在页面解析完毕之后执行jq的ready事件在DOM树生成的时候执行ready先于load执行17,$符号与其他框架发生冲突交出$的使用权:$.noConflict()交权的同时可以使用其他符号代替,例如:var Q=$.noConflict(); 收回$的使用权:jQuery(function($){此处可以使用$})18,鼠标经过事件总结mouseovermouseout以上两个事件绑定给father:鼠标经过father 到son也会触发mouseenter可解决mouseleave以上两个事件绑定给father,经过son时不会触发hover将mousenter和mouseleave两个事件封装成一个事件执行jq对象.hover(function(){ 鼠标移入时执行},function(){ 鼠标移出时执行});$("#warp").hover(function(){$("#inner").stop().animate({bottom:0},1000)},function(){$("#inner").stop().animate({bottom:"-200px"},1000)});jq对象.hover(function(){鼠标移入移出都执行此函数---套路:此方法中实现的切换功能})19,事件的绑定方式:1, jq对象.事件名称(fn);eg:$(“#btn”).click(function(){})2, 用on绑定jq对象.on(“事件名称”,执行任务)写法有多种:$(“#btn”).on(“click mouseover”,fn);$(“#btn”).on({click:fn,moueover:fn});20,解除事件绑定:jq对象.off(“事件名称”,fn)------解绑事件名称执行的fn任务jq对象.off(“事件名称”)---------解绑事件名称执行的所有任务jq对象off()----------------解绑该对象的所有事件的所有任务星星评价二级出现增加21,on绑定事件实现的事件代理---------给未来的元素添加事件父.on(“type”,“子元素”,fn)以上父元素将事件类型代理给子元素(未来的),执行fn任务22,jq的事件对象:注意:jq事件对象中阻止事件冒泡和事件的默认行为只需使用事件对象的方法,兼容性已经处理(2.0)trigger 事件自动只执行(冒泡)triggerHander阻止冒泡23,事件的自动执行jq对象.事件名称()------$(“#btn”).clickjq对象.trigger(“type”)------$(“btn”).trigger(“click”)备注:trgger会执行对象的默认行为,也会发生冒泡jq对象.triggerHandler(“type”)定时轮播备注:不会执行事件的默认行为,会阻止事件冒泡24,动画效果show( )hide( )toggle( )---切换执行show( ) hide( )可以传的速度参数:nomal slow fast 数字slideDown----向下滑开slideUp--------向上收齐animition-delay:数字----------延迟动画执行时间stop 当事件中断时,停止动画继续执行多事件合并执行---------节点1 . 方法1 . 节点2 . 方法2节点2 由节点1确定方法从前到后依次执行$(".banner .bg").fadeTo("fast",.6).attr("src",arr[idx]).fadeTo("fast",1);函数的调用方法:function fun(){}var mytime=setInterval(function(){$("#btn").click()},1000); var mytime=setInterval("$('#btn').click()",1000);var mytime=setInterval(fun,1000);var mytime=setInterval("fun()",1000);25,.offset ( ) 获取元素的当前坐标,坐标相对于文档25,获取窗口的相关尺寸js方法:clientHeight || document.documentElement.clientHeight-------获取页面内容所占的高度document.body.scrollHeight || document.documentElement.scrollHeight ------获取页面滚动的高度jq方法:var h=$(window).outHeight( )=$(window).innerHeight( )-----获取的是窗口的可见高度总结:js无法正常获取,只能通过jq获取窗口的可见高度jq无法获取,只能js获取页面的滚动高度outerHeight()获取窗口可见的边框以内的尺寸offsetHeight$(document).ready(function(){alert($(window).height()); //浏览器当前窗口可视区域高度alert($(document).height()); //浏览器当前窗口文档的高度alert($(document.body).height());//浏览器当前窗口文档body的高度alert($(document.body).outerHeight(true));//浏览器当前窗口文档body的总高度包括border padding margin alert($(window).width()); //浏览器当前窗口可视区域宽度alert($(document).width());//浏览器当前窗口文档对象宽度alert($(document.body).width());//浏览器当前窗口文档body的宽度alert($(document.body).outerWidth(true));//浏览器当前窗口文档body的总宽度包括border padding margin})事件放在引号内购物车--全选解除a标签的自身方法模态框视频1,视频标签<video></video>两种链接资源的方式:1,<video src=”视频资源”>2,<video><source src=”视频资源.mp4”><source src=””视频资源.avi></video>2,可通过标签属性来设置的属性control 控制视屏的控件muted 设置静音autoplay设置视频自动播放以上三个属性直接设置属性表示属性为true 不设置表示false poster 设置视屏暂停是的封面缺点:无法正常设置图片的尺寸解决:不使用该属性,而用定位的方式解决3,视屏中是通过js获取或者设置的属性currentTime视频当前播放时间,可以设置和获取paused获取当前是否处于暂停状态true--暂停false---播放ended 获取视屏是否播放到结尾true----播放完duration 获取视频的整个播放时长只能获取不能设置4,视频播放与暂停的方法play( )------播放pause( )-------暂停var w=$("v1").offsetWidth; 获取内容宽度var h=$("v1").offsetHeight; 获取内容高度补充:.get( index ) 根据索引获取html内容返回值:Element、Array.get() 方法允许我们直接访问jQuery对象中相关的DOM节点。
JQuery开发工具——GVIM。
锋利的jQuery目录第1章认识jQuery (1)第2章jQuery选择器 (2)第3章jQuery的DOM操作 (5)第4章jQuery中的事件和动画 (8)第5章jQuery对表单、表格的操作及更多应用 (11)第6章jQuery与Ajax的应用 (13)第1章认识jQuery1.jQuery的优势:轻量级;强大的选择器;出色的DOM操作的封装;可靠的事件处理机制;完整的Ajax;不污染顶级变量;出色的浏览器兼容性;链式操作方式;隐式迭代;行为层与结构层的分离;丰富的插件支持;完善的文档;开源。
2.使用jQuery之前,要先导入jQuery库。
<script src=”../scripts/jquery-1.3.1.js” type=”text/javascript” />\在jQuery库中,$就是jQuery的一个简写形式,例如$(“#foo”)和jQuery(“#foo”)和document.getElementById(“foo”)是等价的。
Window.onload和$(document).ready()的区别:执行时机:前者必须等待网页中所有的内容加载完毕(包括图片)才能执行;后者在网页中所有DOM结构绘制完毕后就执行,可能DOM元素关联的东西并没有加载完。
编写个数:前者只能编写一个function()块,后者能同时编写多个(多个会依次执行)。
简化写法:前者无;后者$(document).ready(function(){//…})可以简写成:$(function(){//…})3. jQuery代码风格。
链式操作风格:$(".has_children").click( function(){$(this).addClass("highlight") //为当前元素增加highlight类.children("a").show().end() //将子节点的<a>元素显示出来并重新定位到上次操作的元素.siblings().removeClass("highlight")//获取元素的兄弟元素,并去掉它们的highlight类.children("a").hide(); //将兄弟元素下的<a>元素隐藏});代码规范:1)对于同一个对象不超过3个操作的,可以直接写成一行。
Jquery学习笔记1.$(":input[SurveyID='1'][Top][RequireA]").each(function () {$(this)..});筛选SurveyID为1的有Top和RequiredA属性的input元素2.$(this).parents("tr[TopTr]:first")(:last)筛选此元素的父亲tr节点中有topTr属性的第一个tr(最后一个)3.$(this).is("select")是否下拉框.is(":checked")是否选中.is("img")是否图标.is(":text")是否文本.is("input")是否input4.nextObj.css("display", "none")/nextObj.css("display","")/nextObj.css({ top: 0, left: 0, height: h, display: '' });设置隐藏/显示样式/设置几个样式5.parentObj.bind("click", function (){$(this)..})/nextObj.unbind("click")绑定click事件/解除绑定parentObj.bind("focus", function () {$(this)..})焦点事件parentObj.bind("change", function () {$(this)..})内容改变事件parentObj.bind("blur", function () {$(this)..})失去焦点事件parentObj.bind("mouseover", function () {$(this)..})鼠标移过事件parentObj.bind("keyup", function () {$(this)..})松开键盘按钮事件6.curentObj.next('img')/$("#aa").next().is(":visible")获取下一个img的元素对象/是否可见7.curentObj.attr(“id”)/curentObj.attr(“id”,1)/$(this).removeAttr( "id");获取/设置/去掉此对象的id属性8.parentObj.val()/parentObj.val(‘abc’)获取或设置对象的值9.$("div[id^='aa']").each(..)模糊搜索id为aa开头的div10.$(this).get(0).id在object数组里取第一个元素的id11.cObj.find(":selected").attr("OptID")找到选中的元素的OptID属性12.$(":input[name='aa'][type='radio'][checked]") 获取name为aa的一组单选项的选中的对象$(":input[name='aa'][type='checkbox'][checked]") 获取name为aa的一组多选项的选中的对象组13.var resultReq = new Array();resultReq.push('0');把东西装进数组names.pop(1)把1推出去14.var surveyIDs = IDs.split(',');for (var i = 0; i <surveyIDs.length; i++) {if (surveyIDs[i] != ''){}}把IDs按照’分开成一个数组,再根据数组操作15.if(typeof (SetModify) != "undefined")如果此属性存在16.$("#" + id).hide();隐藏.show();显示.click();单击.focus();获得焦点.remove()移除$(this).after(html);在元素后面跟着html字符串.clone()复制当前object$("#aa").text("Downloading...")/.text();设置/获取文本内容17.new Date().getHours()/.getMinutes()/.getTime();获取当前日期时间的小时数/分钟数/时间18.$(newTr).appendTo("#eptb");把newTr放到("#eptb")的里面的最后面19.$(document).ready(function () {});页面元素加载完成后执行的js代码20.$(".redAddress").toggle(true/false);选择用了样式redAddress的元素显示/隐藏21.var startObj = $("#startTime").val();var endObj = $("#endTime").val();var reg_hhmm = /^(?:(?:0?|1)\d|2[0-3]):[0-5]\d$/;if (startObj == '' || endObj == '' || !reg_hhmm.test(startObj) || !reg_hhmm.test(endObj)) {$("#diff").val('');} else {var s1 = new Date("2011-01-01 " + startObj + ":0");var s2 = new Date("2011-01-01 " + endObj + ":0");var s3 = s2.getTime() - s1.getTime();if (s3 > 0) {var h = parseInt(s3 / (60 * 60 * 1000));var m = parseInt(s3 / (60 * 1000)) - h * 60;var result = '';if (h > 0)result = '' + h + 'h';if (m > 0)result += ' ' + m + 'm';$("#diff").val(result);}else {$("#diff").val('0m');}}计算两时间的时间差22.$("#trParent1End").nextAll().not("tr:last").hide();隐藏该table对象不是最后一行tr的所有tr23.if ($.browser.msie) {$("#aa,#bb,#cc").width("151px"); }设置宽度24.$.trim($(this).val())去掉空格。
jquery 中总结十章笔记1. 选择器:- 使用`$()`或`jQuery()`函数来选取DOM元素。
- 可以使用元素名称、类名、ID、属性等进行选择。
- 还可以使用层级关系和过滤器来进一步缩小选择范围。
2. 事件处理:- 使用`on()`方法来绑定事件处理函数。
- 可以使用事件委托来处理动态添加的元素。
- 使用`off()`方法来解绑事件处理函数。
3. DOM操作:- 可以使用`append()`、`prepend()`、`after()`和`before()`方法来插入DOM元素。
- 使用`remove()`方法来删除DOM元素。
- 使用`html()`和`text()`方法来修改元素的HTML内容和文本内容。
4. 动画效果:- 使用`animate()`方法来创建自定义动画效果。
- 可以修改元素的位置、尺寸、透明度等属性。
- 可以设置动画的持续时间、缓动效果和完成时的回调函数。
5. 异步请求:- 使用`$.ajax()`方法发送异步HTTP请求。
- 可以设置请求类型、URL、数据、成功和失败的回调函数等参数。
- 可以使用`$.getJSON()`和`$.post()`等简化的方法来发送常见类型的请求。
6. 特效效果:- 使用jQuery UI库提供的特效效果可以为网页添加交互效果。
- 可以添加拖拽、排序、选项卡、日期选择等功能。
- 可以自定义特效的样式和行为。
7. 表单操作:- 可以使用`val()`方法获取或设置表单元素的值。
- 使用`prop()`方法修改复选框和单选框的选中状态。
- 使用`serialize()`方法将表单元素序列化为字符串。
8. 遍历和过滤:- 使用`each()`方法和回调函数遍历匹配的元素。
- 使用`filter()`和`not()`方法根据条件过滤元素。
- 使用`find()`方法在匹配元素的后代中查找元素。
9. AJAX事件:- 使用`$.ajaxSetup()`方法设置全局AJAX默认选项。
JQUERY1导入两个js和一个css样式<link rel="stylesheet" href="js/css.css" type="text/css"></link> <script type="text/javascript" src="js/jquery1.4.2.js"></script> <script type="text/javascript"src="js/Validform.js"></script>2jquery会和dwr发生冲突,他们默认都是用$给jquery重新声明<script language="javascript">var j = jQuery.noConflict();</script>3淡入淡出的效果实现<script type="text/javascript">j(function(){j("body").hide(1000);j("body").fadeIn(3000);})</script>显示也可以:j("body").show(3000);4让普通按钮变成submit按钮<input type="button" value="提交" id="su">btnSubmit:"#su"5表单触发事件.registerform表单的styleClass="registerform"Validform:为插件点击按钮为#su就会触发jquery函数(j(function(){}))里面的类容自己要定义datatype等要再这个里面(插件)写如果是定义多个要打逗号不打会出不来效果j(".registerform").Validform()加载时就会调用j(".registerform").Validform({btnSubmit:"#su",datatype:{"c":/^[1-9][0-9]{5}(19[0-9]{2}|200[0-9]|2010)(0[1-9]|1[0-2])(0[1-9]|[12][0-9]|3[01])[0-9]{3}[0-9xX]$/}});自己定义datetype:{ "c":符合哪种格式}身份证必须符合这种格式c为上面定义的格式j("#humanIdCard").attr("datatype","c");j("#humanIdCard").attr("errormsg","请输入正确的身份证号码");6验证humanName:是文本框的id属性验证文本框的内容只能是(s2-20)字符2-20个长度j("#humanName").attr("datatype","s2-20");弹出不能为空的信息j("#humanName").attr("nullmsg","姓名不能为空");弹出错误的信息j("#humanName").attr("errormsg","姓名只能在2到20个字符之间");下拉框必须选j("#firstKindId").attr("datatype","select");验证邮箱为:efunction checkEmail(){j("#humanEmail").attr("datatype","e");j("#humanEmail").attr("errormsg","邮箱格式:xx@");if(j("#humanEmail").val()==""){//如果是空的话移除验证j("#humanEmail").removeAttr("datatype");}}Onkeyup:光标放进去再出来时调用验证邮箱的方法Onkeydown: 光标放进去时调用验证邮箱的方法<html:text property="hf.humanEmail" styleId="humanEmail"onkeyup="checkEmail()"/>7拿到下拉框选中的文本,给文本框styleId=firstKindName 赋值拿到文本框的值:j("#firstKindName ").val()j("#firstKindName").val(j("#firstKindId option:selected").text());<html:hidden property="hf.firstKindName" styleId="firstKindName"/>8如果是普通的文本框可以直接这样调用jquery但必须导入那两个文件<input type="text" datetype="s2-20" nullmsg="姓名不能为空" errormsg="姓名只能在2到20个字符之间">9:身份证验证正则表达式"c":/^[1-9][0-9]{5}(19[0-9]{2}|200[0-9]|2010)(0[1-9]|1[0-2])(0[1-9]|[ 12][0-9]|3[01])[0-9]{3}[0-9xX]$/10:datatype类型验证email:e验证邮编:p验证字符:s2-10 …其他还可以在写插件时自己定义10动态创建一个div 元素(以及其中的所有内容),并将它追加到body 元素中$("<div><p>Hello</p></div>").appendTo("body");视频教学第一次课:1JQuery实战第一讲:概述、环境准备及入门实例$.get();($.post())可以完成和服务器端进行交互三个参数urldatacallbackencodeURI(encodeURI(userName)):处理传过去的参数的中文乱码问题$.get("http://127.0.0.1:8080/JQuery/UserVerify?userName=" + encodeURI(encodeURI(userName)),null,function(response){//3.接收服务器端返回的数据,填充到div中$("#result").html(response);});服务器端String userName = URLDecoder.decode(param, "UTF-8");。
FGG_ jquery-1.2学习笔记整理一,jquery-1.2的基本用法1,将jquery-1.2库文件引入到你的项目里面2,在你的页面导入jquery-1.2库<script type="text/javascript" src="jslib/jquery-1.2.js"></script>3,jquery-1.2和java的异步交互function verify() {/*Jquery写法获得节点ID属性var jqueryObj = $("#userName");这样写是获得name属性var jqueryObj = $("input[name='userName']")*/var jqueryObj = $("#userName");/* var userName =$("#userName").val();从 Jquery封装的对象里面获得文本值*/var userName = jqueryObj.val();/*使用 Jquery对XMLHTTPrequest对象get请求的封装他包含3个参数第一个是服务器端的URI 第二个是需要传过去的值第三个是回调函数*/$.get("AjaxServer",{name:userName},huilai);}//回调函数function huilai(huilaide){/*将来ID名为yanzheng的节点值填充为服务器端返回的值相当于document.getElementById("yanzheng").value=huilaide;*/$("#yanzheng").html(huilaide);}/*为function verify() {}和function huilai(huilaide){}的集成写法*/ function verify2(){$.get("AjaxServer",{name: $("#userName").val()},function huilai(huilaide){$("#yanzheng").html(huilaide);});}4,页面代码二,Ajax_XMLHTTPrequest的基本用法ajax.js代码/*XMLHttpRequest基本应用,用户名验证*//*设定一个全局的参数用来创建XMLHttpRequest对象*/var xmlhttp;function ajaxjquery(){/*使用dom的方法获得文本框的值,相当与JQUERY的 $("#userName").val;*/ var userName = document.getElementById("userName").value;/*针对不同的浏览器创建XMLHttpRequest对象*/if(window.XMLHttpRequest){/*针对 FireFox, Mozillar, Opera, Safari, IE7, IE8*/xmlhttp = new XMLHttpRequest();/*针对某些特定版本的mozillar浏览器的BUG进行修正*/if(xmlhttp.overrideMineType){xmlhttp.overrideMineType("text/xml");}}else if(window.ActiveXObject){/*2个可以用来创建XMLHttpRequest对象的控件名称保存在一个数组中*/var activexName = ["MSXML2.XMLTTP","Microsoft.XMLHTTP"];for(var i = 0; i<activexName.length;i++){try{/*针对IE7版本以下*/xmlhttp = new ActiveXObject(activexName[i]);break;}catch(e){}}}if(!xmlhttp){alert("XMLHttpRequest对象创建失败,请更换更高版本的浏览器以保证您的正确浏览");return;}else{alert(xmlhttp);/*注册回调函数*/xmlhttp.onreadystatechange = huilai;/*设置连接信息,第一,设置请求方式 get/post,第二,设置请求URL,第三设置是同步请求还是异步true 表示异步 false是同步*/xmlhttp.open("GET","AjaxJQuery?userName="+userName,true);/*发送数据和服务器交互*/xmlhttp.send(null);/*-----------如果采用POST方法提交写法不同----------------xmlhttp.open("POST","AjaxJQuery",true);//需要设置请求头xmlhttp.setRequestHeader("Content-Type","application/x-www-form-u rlencoded");//POST方法发送数据xmlhttp.send("userName=" + userName);----------------------------------------------------*/ }}function huilai(){/*判断数据交互完成的状态为 4*/if(xmlhttp.readyState==4){/*判断数据交互是否成功*/if(xmlhttp.status == 200){/*纯文本的方式获得数据*/var responseText = xmlhttp.responseText;/*-------获得XML数据--------------------------//<message>假如标签名为message</message>var domObj = xmlhttp.responseXML;if(domObj){var messageNodes= domObj.getElementsByTagName("message");if(messageNodes.length>0){//获得文本节点var textNode = messageNodes[0].firstChild;//获得文本节点的内容var responseMessage = textNode.nodValue;//现实到页面var spanNode =document.getElementById("yanzheng").innerHTML = responseMessage;}}--------------------------------------------*/document.getElementById("yanzheng").innerHTML = responseText;}}}HTML页面代码<html><head><script type="text/javascript" src="jsserver/ajax.js"></script></head><body><h1>XMLHttpRequest简单应用(一)用户名验证</h1><hr /><form action=""><input type="text" id="userName" /><span id="yanzheng"></span><br><input type="button" value="验证" onclick="ajaxjquery()"/></form><br></body></html>服务器端代码public void doPost(HttpServletRequest request, HttpServletResponse response)throws ServletException, IOException {response.setContentType("text/html");PrintWriter out = response.getWriter();String userNameString = request.getParameter("userName");System.out.println(userNameString);if(userNameString==null || userNameString.length()<=0){out.print("UserName Null");}else{out.print("UserName: "+userNameString+" :YES");}out.flush();out.close();}web.xml<servlet><servlet-name>AjaxJQuery</servlet-name><servlet-class>com.fggajax.server.AjaxJQuery</servlet-class></servlet><servlet-mapping><servlet-name>AjaxJQuery</servlet-name><url-pattern>/AjaxJQuery</url-pattern></servlet-mapping>三,jquery读取XML的基本用法ajax.js代码function AJAXXMLS(){var userName = $("#userName").val();/*jquery封装好的异步交互方法也可以用$.get()和$.post()方法*/$.ajax({type:"POST", //设置交互方式url:"AJAXXMLServer",//设置交互urldata:"userName="+userName,//设置交互的数据dataType:"xml",//告诉jquery返回数据的各式success:huilai//设置回调方法});}function huilai(data){/*dom方式获得标签对象转换成jquery对象*/var jqueryObj = $(data);/*获得XML标签名字*/var message =jqueryObj.children();/*获得XML标签内的文本内容*/var text = message.text();/*将XML文本内容动态现实在页面的<span>标签文本中*/$("#yanzheng").html(text);}HTML页面代码<body><h1>Jquery读取XML各式文件的简单应用:用户名验证</h1><hr /><form action=""><input type="text" id="userName" /><span id="yanzheng"></span><br><input type="button" value="验证" onclick="AJAXXMLS()"/></form></body>服务器端代码public void doPost(HttpServletRequest request, HttpServletResponse response)throws ServletException, IOException {response.setContentType("text/xml; charset=gbk");PrintWriter out = response.getWriter();String userNameString = request.getParameter("userName");System.out.println(userNameString);StringBuilder builder = new StringBuilder();builder.append("<message>");if(userNameString == null || userNameString.length()==0){ builder.append("userName NULL").append("</message>");}else{builder.append("userName: "+userNameString+"YES").append("</message>");}out.println(builder.toString());System.out.println(builder.toString());out.flush();out.close();}web.xml<servlet><servlet-name>AJAXXMLServer</servlet-name><servlet-class>com.fggajax.server.AJAXXMLServer</servlet-class> </servlet><servlet-mapping><servlet-name>AJAXXMLServer</servlet-name><url-pattern>/AJAXXMLServer</url-pattern></servlet-mapping>四,URL添加时间戳骗过IE不读缓存ajax.js代码/*为ajaxjquery(url)提供url值*/function fushuai(){var userName = $('#userName').val();ajaxjquery("JqueryUrl?userName="+userName);}function ajaxjquery(url){var url2 = converURL(url);$.get(url2,null,function huilai(fushuai){$("#yanzheng").html(url2+" : "+fushuai);});}/*给url地址增加一个时间戳骗过浏览器不读取缓存*/function converURL(url){/*获得时间戳*/var timtamp = (new Date()).valueOf();/*将时间戳拼接到url上*/if(url.indexOf("?")>=0){url =url+"&t="+timtamp;}else {url =url+"?t="+timtamp;}return url;}HTML页面代码<body><h1>给URL添加一个时间戳骗过部分浏览器不读取缓存</h1><hr /><form action=""><input type="text" id="userName" /><span id="yanzheng"></span><br><input type="button" value="验证" onclick="fushuai()"/></form><br></body>服务器端代码public void doGet(HttpServletRequest request, HttpServletResponse response)throws ServletException, IOException {response.setContentType("text/html; charset=gbk");PrintWriter out = response.getWriter();Integer integer =(Integer)request.getSession().getAttribute("ints");int ints = 0;if(integer==null){ints =1;}else{ints = integer.intValue()+1;}request.getSession().setAttribute("ints",ints);String userNameString = request.getParameter("userName");out.print(userNameString+" : "+ints);out.flush();out.close();}web.xml<servlet><servlet-name>JqueryUrl</servlet-name><servlet-class>com.fggajax.server.JqueryUrl</servlet-class> </servlet><servlet-mapping><servlet-name>JqueryUrl</servlet-name><url-pattern>/JqueryUrl</url-pattern></servlet-mapping>五,JQuery控制浮动窗口ajax.js代码function showwin(){/*获得节点对象后使用.css方法控制CSS样式*///$("#win").css("display","block");/*Jquery的show方法控制显示速度*///$("#win").show("slow");/*Jquery的fadeIn方法实现淡入淡出效果 */$("#win").fadeIn("slow");}function hide(){/*注意使用什么方法开启就必须有相对应的方法关闭*///$("#win").css("display","none");//$("#win").hide("slow");$("#win").fadeOut("slow");}CSS代码#win{/*id选择器*/border: 1px red solid;width: 200px;height: 200px;position: absolute;/*结对位置*/top: 100px;left: 100px;display: none;/*初始化窗口不可见*/}#div1{background-color: blue;/*控制栏目的背景颜色*/color: ywllow;/*控制栏目中的字体颜色*/padding-left: 3px;/*控制栏目的左内边距*/}#div2{padding-left: 3px;padding-top:5px;}#span1{/*控制开关按钮*/margin-left: 158px;/*是关闭开关向右移动*/cursor: pointer;/*让鼠标悬停时出现一个手指*/}HTML代码<script type="text/javascript"src="jquerylib/jquery-1.2.js"></script><script type="text/javascript" src="js/jquerywin.js"></script><link rel="stylesheet" href="css/divwin.css" type="text/css" /></head><body><h1>的JQuery实例1:浮动窗口</h1><hr /><a onclick="showwin()" href="#">显示浮动</a><!-- 使用DIV来表示弹出框,CC控制显示效果--><div id="win"><div id="div1"><span id="span1" onclick="hide()">关闭</span></div><div id="div2">内容栏目</div></div></body>六,JQuery实现弹出菜单和动态装载ajax.js代码/*页面加载时执行JS方法*/$(document).ready(function(){/*给所有的ul菜单注册点击事件*///$("ul").click(function(){/*给ul下面的span注册单击事件*/$("ul>span").click(function(){/*找到当前节点的子节点*///var lis = $(this).children("li");/*找到当前span节点的兄弟节点*/var lis = $(this).nextAll("li");/*loggle可切换元素的显示状态关闭时开启,开启时关闭*/lis.toggle("show");});$("li > div").click(function(){/*load方法可以动态装载另外一个页面到当前节点内*/$("#fushuai").load($(this).attr("id"));});});css代码li {list-style: none;/*设置LI的小黑点消失*/margin-left: 18px;/*控制边距*/display: none;/*先把子菜单隐藏*/}span{cursor: pointer ;/*让鼠标悬停时出现一个手指*/}html代码<link rel="stylesheet" href="css/JQueryMenu.css"type="text/css"></link><script type="text/javascript"src="jquerylib/jquery-1.2.js"></script><script type="text/javascript" src="js/JQueryMenu.js"></script> </head><body><h1>JQuery弹出菜单</h1><hr /><ul><span>三八停总店</span><li><div id="JqueryWindow.jsp">春花分店</div></li><li><div>车车分店</div></li></ul><ul><span>沿河街总店</span><li><div>小草伊人分店</div></li><li><div>和尚洗头分店</div></li></ul><div id="fushuai"></div></body>七,JQuery实现可编辑文本AJAX代码/*在页面装载时候给让TD拥有一个点击事件*/$(document).ready(function(){/*点击TD的事件*/var tds = $("td").click(function fushuai(){/*取到当前TD的文本内容*/var tdtext = $(this).text();/*清空TD的文本值,可以使用remove清空*/$(this).html("");/*创建<input>节点,如果没有<>就是找到节点*/var input =$("<input>");/*设置文本的属性值*/input.attr("value",tdtext);input.attr("size",18);/*设置input响应键盘事件*/input.keyup(function(event){/*解决浏览器对象的差异*/var myevent =event || window.event;/*判断按下并弹起的是那个键*/if(myevent.keyCode==13){var inputval=$(this).val();/*获得当前原属的父原属*/var tdn = $(this).parent();/*将input的val填充到他的父原属的文本中*/tdn.html(inputval);/*父原属重新获得单击事件,递归方式获得单击事件*/tdn.click(fushuai);}});/*将文本框加入到TD中*///input.appendTo($("this"));$(this).append(input);/*文本框内容被全部选中*/input.get(0).select();/*移除当前TD上的点击事件*/$(this).unbind("click");});});html代码<link rel="stylesheet" href="css/JQueryEdit.css"type="text/css"></link><script type="text/javascript"src="jquerylib/jquery-1.2.js"></script><script type="text/javascript"src="js/JQueryEdit.js"></script></head><body><h1>JQuery实现可编辑文本</h1><hr /><!-- 一个简单的表格一行两列 --><table align="center" width="240"><tbody><tr><td width="120" height="24">fushuai1</td><td width="120" height="24">fushuai2</td></tr></tbody></table></body>CSS代码table,td{/*让相邻的边框全部合并*/border-collapse: collapse;;border: 1px solid black;/*设置边框的像素*/}八,jquery/json数据实现股市行情AJAX代码/*全局变量保存服务器返回的股票对象*/var objs;/*objs的节点对象*/var div1s;/*进入页面装载数据*/$(document).ready(function(){getInfo();/*每过1000毫秒调用一次getInfo方法*/setInterval(getInfo,1000);var divStock=$("#stock").css("border","1px solid black").css("width","200px").css("position","absolute").css("z-index","99").css("background-color","blue");/*页面加载时隐藏弹出框*/divStock.hide();var b=$("b").css("cursor","pointer");;/*鼠标进入*/b.mouseover(function(event){var b1=$(this);/*获得节点ID的名字*/div1s= b1.parent().attr("id");fushuai();/*找到当前对象的位置,返回的值是左边界和上边界的值*/var offset = b1.offset();/*设置弹出框的 left top的位置等于当前原属的位置*/divStock.css("left",offset.left+70+"px").css("top",offset.top+b1.height()+20+"px");/*设置弹出框的 left top的位置在鼠标的X,Y轴的后10pxvar myEvent = event || window.event;divStock.css("left",myEvent.clientX + 10 +"px").css("top",myEvent.clientY + 10 +"px");*/divStock.show();});/*鼠标离开*/b.mouseout(function(){divStock.hide();});});/*给url地址增加一个时间戳骗过浏览器不读取缓存*/function converURL(url){/*获得时间戳*/var timtamp = (new Date()).valueOf();/*将时间戳拼接到url上*/if(url.indexOf("?")>=0){url =url+"&t="+timtamp;}else {url =url+"?t="+timtamp;}return url;}/*想服务器端发起请求,获得数据*/function getInfo(){var url = converURL("GetStocksInfo");$.get(url,null,function(data){/*接受并解析Json数据格式的对象*/objs=eval(data);/*get方法后面加个值json就不需要再用eval转换json格式里面的对象了在返回的时候就被JQuery转换过来了*///objs=data;/*获取两只股票的当前指数*/var szzs=objs["300001"];var pfyh=objs["000001"];/*获得页面中对应的节点然后填充最新的股票价格*/var span1 = $("#300001").children("span");span1.html(szzs.now);if(szzs.now > szzs.yes){span1.css("color","red");}else{span1.css("color","green");}/*找到#000001下的SPAN 节点对象*/var span2 = $("#000001").children("span");span2.html(pfyh.now);if(pfyh.now > pfyh.yes){span2.css("color","red");}else{span2.css("color","green");}fushuai();}/*,"json"*/);}function fushuai(){var stockobj = objs[div1s];for(var var1 in stockobj){if(var1 != name){$("#"+var1).children("span").html(stockobj[var1]);}}}}Servlet代码package com.jquery.bens;import java.io.IOException;import java.io.PrintWriter;import java.util.HashMap;import javax.servlet.ServletException;import javax.servlet.http.HttpServlet;import javax.servlet.http.HttpServletRequest;import javax.servlet.http.HttpServletResponse;public class GetStocksInfo extends HttpServlet {private HashMap<String, Stock>stocks;public HashMap<String, Stock> getStocks() {return stocks;}public void setStocks(HashMap<String, Stock> stocks) {this.stocks = stocks;}@Overridepublic void init() throws ServletException {stocks =new HashMap<String, Stock>();//创建股票Stock szzs = new Stock(3000.0,2990.1,"上证指数","300001");Stock pfyh = new Stock(23.23,23.50,"浦发银行","000001");//将2只股票存放在stocks的map中stocks.put(szzs.getId(), szzs);stocks.put(pfyh.getId(), pfyh);System.out.println(stocks);}public void doGet(HttpServletRequest request, HttpServletResponse response)throws ServletException, IOException {response.setContentType("text/html; charset=gbk");PrintWriter out = response.getWriter();/**返回两只股票的信息*//**计算随机数*/double sz = Math.random() * 20;double pf = Math.random() * 0.5;/**控制随即数是涨还是跌*/boolean szs = ((int)(Math.random() * 20)%2==0);boolean pfs = ((int)(Math.random() * 10)%2==0);/**将随即数和当前股票价格进行加或者减*/Stock szzs = stocks.get("300001");Stock pfyh = stocks.get("000001");double temp;if(szs){temp = szzs.getNow() + sz;}else {temp = szzs.getNow() - sz;}temp = (int)(temp*100)/100.0;szzs.setNow(temp);if(pfs){temp = pfyh.getNow() + pf;}else {temp = pfyh.getNow() - pf;}temp = (int)(temp*100)/100.0;pfyh.setNow(temp);//out.println(szzs+"<br />"+pfyh);/**采用Json的数据格式返回2只股票的昨天收盘,今天开盘和当前价格*/StringBuilder builder = new StringBuilder();/**数组的方式builder.append("[{name:\"").append(szzs.getName()).append("\",id: \"").append(szzs.getId()).append("\",yes:").append(szzs.getYesterday()+",").append("tod:"+ szzs.getToday()+",").append("yess:"+szzs.getNow()+"},").append("{name:\"").append(pfy h.getName()).append("\",id:\"").append(pfyh.getId()).append("\",yes:").append(pfyh.getYesterday( )+",tod:").append(pfyh.getToday()).append(",yess:").append(pfyh.getNow()).append("}]");*//**对象的方式*/builder.append("({\""+szzs.getId()+"\":{name:\"").append(szzs.getName()).append("\",").append("yes:").append(szzs.getYesterday()).append(",tod:"+szzs.getToday()).append(",now:"+szzs.getNow()+"},").append("\""+pfyh.getId()+"\":{name:\"").append(pfyh.getName()).append("\",").append("yes:").append(pfyh.getYesterday()+",tod:").append(pfyh.getToday()).append(",now:").append(pfyh.getNow()).append("}})");out.print(builder);System.out.println(builder);}public void doPost(HttpServletRequest request, HttpServletResponse response)throws ServletException, IOException {doGet(request, response);}}JavaBean代码package com.jquery.bens;public class Stock {/**股票name*/private String name;/**股票id*/private String id;/**股票昨天收盘价*/private double yesterday;/**股票今天开盘价*/private double today;/**股票当天价*/private double now;public Stock(double yesterday,double today,String name,String id){ this.yesterday = yesterday;this.today = today; = name;this.id = id;this.now = today;}public String getName() {return name;}public void setName(String name) { = name;}public String getId() {return id;}public void setId(String id) {this.id = id;}public double getYesterday() {return yesterday;}public void setYesterday(double yesterday) {this.yesterday = yesterday;}public double getToday() {return today;}public void setToday(double today) {this.today = today;}public double getNow() {return now;}public void setNow(double now) {this.now = now;}public String toString() {return +":"+this.now;}}html代码<script type="text/javascript"src="jquerylib/jquery-1.2.js"></script><script type="text/javascript" src="js/GetStocksInfo.js"></script> </head><body><h1>使用Json数据格式动态股票信息</h1><hr /><div id="300001"><b>上证指数:</b><span></span></div><div id="000001"><b>浦发银行:</b><span></span></div><div id="stock"><div id="yes">昨天收盘:<span id=""></span></div><div id="tod">今天开盘:<span id=""></span></div><div id="now">当天指数:<span id=""></span></div></div></body>Web.xml代码<servlet><servlet-name>GetStocksInfo</servlet-name><servlet-class>com.jquery.bens.GetStocksInfo</servlet-class><load-on-startup>1</load-on-startup></servlet><servlet-mapping><servlet-name>GetStocksInfo</servlet-name><url-pattern>/GetStocksInfo</url-pattern></servlet-mapping>九,jquery-1.2模仿百度搜索栏客户端代码ajax代码这个实例需要JQuery1.3版本支持/*控制索引值*/var fushuiInt =-1;/*获得提交延迟值*/var timoutId;$(document).ready(function(){/*文本框*/var wordNodes = $("#word");var wordNodestype = wordNodes.offset();/*隐藏自动补全提示框*/$("#auto").hide().css("position","absolute").css("border","1px black solid").css("left",wordNodestype.left+"px").css("top",wordNodestype.top+wordNodes.height()+7+"px").css("width",wordNodes.width()+4);/*给文本框添加一个键盘按下并弹起的事件*/wordNodes.keyup(function(event){var myEvent = event || window.event;var keyCode = myEvent.keyCode;/*判断键盘输入不同的键做不同的抄作,参数参考键码表*//*aA-zZ*//*退格*//*Del*/if(keyCode>=65 &&keyCode<=90 ||keyCode==8 ||keyCode==46){ /*获得文本框内容*/var wordText = wordNodes.val();/*文本内容不为空才想服务器端请求*/var autoNodes = $("#auto");if(wordText!=""){/*上次提交未完成的话就取消抄作,* 以减少用户在输入未完成的情况下向服务器发送请求*/clearTimeout(timoutId);/*对用户提交数据进行延迟500毫秒发送,它会返回延迟值*/timoutId = setTimeout(function(){/*将文本框内容发送到服务器*/$.get("AutoComlete",{word:wordText},function(data){/*将dom对象的data转换成JQuery的对象*/var jqueryObj = $(data);/*找到<word>节点*/var wordNodes = jqueryObj.find("word");autoNodes.html("");/*用each方法遍历word取出类容,然后将内容添加到弹出框这个方法携带2个参数一个是集合的索引号,一个是索引对应的值*/wordNodes.each(function(i){var wordNodes = $(this);/*找到一个内容就创建一个DIV并将内容添加到DIV内*/var newDivNode= $("<div>").attr("id",i);newDivNode.html(wordNodes.text()).appendTo(autoNodes);/*鼠标进入*/newDivNode.mouseover(function(){if(fushuiInt !=-1){$("#auto").children("div").eq(fushuiInt).css("background-color","white");}fushuiInt = $(this).attr("id");$(this).css("background-color","red").css("cursor","pointer");});/*鼠标离开*/newDivNode.mouseout(function(){$(this).css("background-color","white");fushuiInt=-1;});/*鼠标单击*/newDivNode.click(function(){var thisText = $(this).text();$("#word").val(thisText);$("#auto").hide();fushuiInt=-1;alerts();/*提交服务器方法*/});});if(wordNodes.length > 0){/*如果找的到节点对象就现实自动补全提示框*/autoNodes.show();}else{autoNodes.hide();fushuiInt =-1;}},"xml");},"1000");}else{autoNodes.hide();fushuiInt =-1;}}else if(keyCode == 38 || keyCode == 40){if(keyCode == 38){/*按向上*/var autodiv= $("#auto").children("div");if(fushuiInt!=-1){/*eq取这个的对象集合中的第 int 个对象*/autodiv.eq(fushuiInt).css("background-color","white");fushuiInt--;}else{fushuiInt =autodiv.length -1;}if(fushuiInt ==-1){fushuiInt = autodiv.length -1;}else{autodiv.eq(fushuiInt).css("background-color","red");}}if(keyCode == 40){/*按向下*/var autodiv= $("#auto").children("div");if(fushuiInt!=-1){autodiv.eq(fushuiInt).css("background-color","white");}fushuiInt++;if(fushuiInt==autodiv.length){fushuiInt = 0;}autodiv.eq(fushuiInt).css("background-color","red");}}else if(keyCode == 13){/*回车*/if(fushuiInt!=-1){var comText =$("#auto").children("div").eq(fushuiInt).text();$("#auto").hide();$("#word").val(comText);fushuiInt=-1;alerts();/*提交服务器方法*/}else{}}});/*按提交按钮的时候触发事件*/$("input[type='button']").click(function(){alerts();});function alerts(){$("#auto").hide();fushuiInt =-1;alert("数据【 "+wordNodes.val()+" 】被提交到服务器");}});HTML代码<script type="text/javascript"src="jquerylib/jquery-1.3.js"></script><script type="text/javascript"src="js/AutoComlete.js"></script></head><body><h1>JQuery实现搜索引擎的自动补全效果</h1><hr />------------------------------------<input type="text"id="word"/><input type="button" value="付帅一下" /><br><div id="auto"></div></body>JSP代码<%@ page language="java" contentType="text/xml; charset=utf-8"%> <%String word =(String)request.getParameter("word");%><words><%if("ajax".startsWith(word)){%><word>ajax</word><%}if("apple".startsWith(word)){%><word>apple</word><%}if("ajavaScript".startsWith(word)){%><word>ajavaScript</word><%}if("ajax niu".startsWith(word)){%><word>ajax niu</word><%}if("ajax lousui".startsWith(word)){%><word>ajax lousui</word><%}if("fushuai".startsWith(word)){%><word>fushuai</word><%}if("b sun".startsWith(word)){%><word>b sun</word><%}if("sun b".startsWith(word)){%><word>sun b</word><%}if("niub".startsWith(word)){%><word>niub</word><%}if("cctv".startsWith(word)){%><word>cctv</word><%}if("ccttv".startsWith(word)){%><word>ccttv</word><%}if("lcc".startsWith(word)){%><word>lcc</word><%}if("ajaxsssss".startsWith(word)){%><word>ajaxsssss</word><%}if("fgg go".startsWith(word)){%><word>fgg go</word><%}if("bbcc".startsWith(word)){%><word>bbcc</word><%}if("ccbb".startsWith(word)){%>。
jqeury方法笔记
一、简介与背景
随着Web前端技术的不断发展,JavaScript库的应用变得越来越普及。
其中,jQuery作为一个功能丰富、易于使用的库,受到了许多开发者的喜爱。
本文将对jQuery方法进行详细的梳理和总结,以帮助读者更好地理解和应用jQuery。
二、jQuery方法概述
1.选择器
jQuery提供了一系列强大的选择器,可以方便地选取页面中的元素。
如:$("selector")、$(".class")、$("[attribute]")等。
2.动画与特效
jQuery内置了许多动画效果,如fadeIn、fadeOut、slideUp、slideDown等。
通过这些动画效果,可以轻松地为网页元素添加动态展示。
3.事件处理
jQuery提供了便捷的事件处理方法,如绑定事件、冒泡和捕获等。
可以使用如:$(selector).on("event", function())等方法进行事件处理。
4.异步编程
jQuery支持异步编程,如AJAX请求。
使用$.ajax()方法可以方便地发起GET、POST等类型的请求,实现与服务器的数据交互。
5.实用工具
jQuery还提供了一些实用工具,如$.each()、$.map()、$.parseHTML()
等,便于开发者进行复杂的DOM操作和数据处理。
一、Retrieving Page Content1.SELECTORS<script type="text/javascript" src="../jquery-1.3.2.js"></script><script type="text/javascript">$("document").ready(function() {//选择器$("ul .a").css("border","3px solid red");$("#list1~p").css("border","3px solid red");$("div>.a").css("border","3px solid red");});</script>选择器的用法$(" "). 引号内容selector,selector……Finds all of the specified selectors.calss1 .calss2Finds all elements with both .class1 and .class2 parent>child Finds all child elements that are direct children of elements of type parentancestor descendantFinds all descendant elements that are contained within elements of type ancestorprev+nextFinds all next elements that are next to a prev elementprev~siblingsFinds all sibling elements that come after prev and match the siblings selector2.FIL TERSUSING BASIC JQUERY FILTERS:firstSelects only the first instance of the selector's returned set:last :even :od d:eq(n)Filters out elements that are not positioned at the given index:gt(n)Includes elements that are past the given index 从零开始编号:lt(n)Includes elements that are before the given index:head erSelects all header elements(H1,H2,H3,etc):animatedSelects all elements that are currently being animated in some way :not(selector)Includes elements that do not match the given selector用法举例:$("p:first").css("border","3px solid red");//第一个p段落被修饰$("p:gt(1)")…//大于1,从第三个p段落开始$(".a:odd")…//奇数$("p:not(p:eq(2))")…//去掉第三个p段落ATTRIBUTES FILTERS[attribute]Includes elements in the result set if they have the specified attribute[attribute=value]Includes elements in the result set if they have the specified attribute and it has the given value [attribute!=value]……doesn't have the given value[attribute^=value]……and it starts with the specified value[attribute$=value]……and it ends with the specified value[attribute*=value]……and it contains with the specified value[attrFilter1][attrFilterN]match allCONTENT FILTERS:contains(text)Filters the selection to only include elements that contain the text string :emptyFilters the selection to only include empty elements:has(selector)$("ul:has(li[class=a])"):parentMatches all elements that are parents $("p:parent") VISIBILITY FILTERS:visibleFilters the selection to only include visible elements:hid d enFilters the selection to only include hidden elements$("p:hidden") <p></p>CHILD FILTERS:nth-child(ind ex) $("ul li:nth-child(3)"):nth-child(even):nth-child(od d):nth-child(equation)i.e. 2n or 3n+1 $("ul li:nth-child(2n)"):first-child:last-child:only-childFORM SELECTORS:input :text :password :radio :checkbox :submit :reset :image:button :file :enabled :disabled :checked :selected$("form :text:enabled")3.TRAVERSING DOCUMENT INFOMATIONsize(),lengthThe number of elements in the jQuery result setget()Returns an array of all matched DOM eful if you need to operate on the DOMelements themselves instead of using built-in jQuery functionsget(ind ex)Access a single matched DOM element at a specified index in the matched setfind(expression)Searches for descendent elements that match the specified expression$("ul").find("li.b").css……each(fn) Execute a function within the context of every matched element<script type="text/javascript" src="../jquery-1.3.2.js"></script><script type="text/javascript">$("document").ready(function() {//each(fn)的用法var leftmargin = 0;var border = 3;$("p").each(function(){$(this).css("border",border +"px solid red");$(this).css("margin-left", leftmargin);border += 2;leftmargin += 10;});</script>4.JQUERY STATEMENT CHAININGOne of jQuery's most powerful features is its ability to chain multiple functions together to perform several operations in one line of code$(selector).fn1().fn2().fn3();$("a[href$=.pdf]").after("code") 在href属性值以“.pdf”结束的a元素节点后插入HTML 代码code二、Manipulating Page Content1.CREATING,SETTING,AND GETTING CONTENTvar newHeader = $("<h1>My New Header<h1>");var myStr = "<h1>My New Header<h1>";var newHeader = $(myStr);html()Return the HTML content of the first matched elementhtml(newcontent)Sets the HTML content of every matched elementtext()Returns the text content of the first matched elementtext(newtext)Sets the text content for all matched elements2.MANOPULATING ATTRIBUTES attrattr(name)Access property on the first matched element.This method makes it easy to retieve a property value rom the first matched element.If the element does not have an attribute with such a name,undefined is returnedattr(properties)Sets a series of attributes on all matched elements using an object notation syntax.This is the best used for setting large numbers of properties at onceattr(key,value)Sets a single propety to a value on all matched elementsattr(key,fn)Sets a single property to a computed value,on all matched element.Instead of supplying a string value,a function is provided that computes the value of the attriuteremoveAttr(name)Removes the named attribute from all matched elements$("a").attr({href:"images/Leaf.jpg"});$("img").attr({src:"images/Leaf.jpg",alt:"Leaf"});3.INSERTING CONTENTappend(content)Appends content to the inside of every matched element 后加appendTo(selector)Appends all of the matched elements to another,specified,set of elementsprepend(content)Prepends content to the inside of every matched dlement 前加prependTo(selector)Prepends all of the matched elements to another,specified,set of elementsafter(content)Insert content after each of the matched elementsbefore(content)Insert content before each of the matched elementsinsertAfter(sel ector)Inserts all of the matched elements after another,specified,set of elements insertBefore(selector)Inserts all of the matched elements before another,specified,set of elements$("#list1").after("<a>1</a>");$("p.a").prepend("appended");$("p:last").prependTo("p:first");("p:last").insertAfter("p:first");4.WRAPPING,REPLACING,REMOVING CONTENTwrap(html)Wraps each matched element with the specified HTML contentwrap(element)Wraps each matched element with the specified elementwrapAll(html)Wraps all the elements in the matched set with the specified HTML contentwrapAll(element)] Wraps all the elements in the matched set into a single wrapper elementwrapInner(html)Wraps the inner child contents of each matched element(including text nodes)with an HTML structurewrapInner(element)Wraps the inner child contents of each matched element(including texy nodes)with an DOM structurereplaceWith(content)Replaces all matched elements with the specified HTML or DOM elementsreplaceAll(selecctor)Replaces the elements matched by the specified selector with the matched elementsempty()Removes all child nodes from the set of matched elementsremove()Removes all matched elements from the DOMclone()Clone matched DOM elements and selects the clonesclone(bool)Clone matched DOM elements,and all their event handlers,and select the clones$("p").wrap("<div style='border:3px solid red' />");$("p").wrapAll("<div style='border:3px solid red' />");$("p").wrapAll("<div>");5.WORKING WITH CSS INFORMATIONcss(name)Returns the value for the named CSS property for the first matched elementcss(property)Sets the CSS properties of every matched element using an object-notation syntax: var cssObj = {'background-color':'#ddd','font-weight':'','color':'rgb(0,40,244)'}$(this).css(cssObj);css(property,value)6. WORKING WITH CSS CLASSESad dClass(class)Adds the specified class(es) to each of the set of matched elementshasClass(class)Returns ture if...removeClass(class)Removes all the specified class(es) from the set of matched elements toggleClass(class)Adds the specified class if it is not present,removes the specified class if it is present toggleClass(class,switch)Adds the specified class if the switch id ture,removes the specified class if the switch is false7.WORKING WITH CSS POSITIONINGoffset()Gets the current offset of the first matched element,in pixels,relative to the document offsetParent()Returns a jQuery collection with the positioned parent of the first matched element position()Gets the top and left position of an element relative to its offset parentscrollT op()Gets the scroll top offset of the first matched elementscrollT op(val)Sets the scroll top offset to the given value on all matched elements scrollLeft()Gets the scroll left offset of the first matched elementscrollLeft(val)Sets the scroll left offset to given value on all matched elements8.WORKING WITH CSS SIZING INFORMATION height()Gets the current coputed,pixel,height of the first matched elementheight(val)Setswidth()width(val)innerHeight()Gets the inner height(excluding the border and including the padding) for the first matched elementinnerWidth()outerHeight(margin)Gets the outer height(includes the border and padding by default)for the first matched element. If the margin argument id true,then the margin values are also includedouterWidth(margin)innerWidth(Height) = width(height) + paddingouterWidth(Height) = width(height) + padding + border (+ margin)div#theDiv {width: 250px;height: 180px;margin: 10px;padding: 20px;background: blue;border: 2px solid black;cursor: pointer;}$("#theDiv").outerHeight()height(180px)+2*padding(20px)+2*border(2px)=224px$("#theDiv").outerHeight(true)height(180px)+2*padding(20px)+2*border(2px)+2*margin(10px)=244pxfunction buildBookmarks(strWhichTag, sBookMarkNode) {var i;var cAnchorCount = 0;// create the list that will hold the bookmark linksvar oList = $("<ul id='bookmarksList'>");// for each one of the header tags, create a new named anchor and insert it into// the header tag. Then add a new link to the list that points to the named anchor$("div:not([id=header]) " + strWhichTag).each(function() {$(this).html("<a name='bookmark" + cAnchorCount + "'></a>" + $(this).html());oList.append($("<li><a href='#bookmark" + cAnchorCount++ + "'> " + $(this).text() + "</a></li>"));});// now find the ID of the bookmark container and append it$("#" + sBookMarkNode).append(oList);}this指传进来的对象要学会用each()each(fn) Execute a function within the context of every matched element三、WORKING WITH EVENTS1.JQUERY EVENT FUNCTIONSEvents are connected to and disconnected from elements using the bind() and unbind() functions$(selector).bind(event,data,handler)$(selector).unbind(event,handler)BIND()-----------PARAMETER PURPOSE--------eventDefines the event that you want to bound to for each element in the selector's result set.Possible-values-are:blur,focus,load,resize,scroll,unload,beforeunload,click,dbclick,mousedown ,mouseup,mouseover,mousemove,mouseout,mouseenter,mouseleave,change,select,submit,keyd own,keypress,keyup,errordataOptional.Defines a piece of data that will be passed to the handler function whe n the event happens and the handler function is calledhandlerSpecified the function that will hand the eventUNBIND()-----------PARAMETER PURPOSE--------eventDefines the event that you want to be disconnected for each element in the selector's result sethandlerSpecified the handler function that was defined to handle the event2.CONVENIENT JQUERY EVENT HELPER FUNCTIONS$(selector).click(fn)$(selector).hover(fnOver,fnOut)$(selector).toggle(fn1,fn2,fn3,fn4...)3.JQUERY EVENT OBJECTtypeType of the event("click",e.g.)targetElement that issued the eventdataData passed to bind functiontimestampTime when event occurredpreventDefault()revents the brower from ececuting the default actionisDefaultPrevented()Returns whether preventDefault() was ever called on this projectstopPropagation()Stops the bubbling of an event to parent elementsisPropagationStopped()Returns whether stopPropagation() was ever called on this object4.MISCELLANEOUS(各种各样的,不同性质的) JQUERY EVENT FUNCTIONSone(type,data,handler)Works the same as bind(),but the event handler is only ever executed one time for each matched elementtrigger(event,data)Triggers an event on every matched element.This will also cause the default action of the browser to be executed.For example,passing 'click' to the trigger() function will also cause the browser to act as though the item were clickedtriggerHandler(event,data)Triggers all bound event handlers on an element(for a specified event type)without executing the browser's default actions,bubbling,or live events.Only works on the first matched element in the result set for selector<script type="text/javascript" src="../jquery-1.3.2.js"></script><script type="text/javascript">$(function() {$("div").one("click",function(evt){$(this).css({background:"red",cursor:"auto"});});});</script>一个疑惑的问题:.even {background-color:#9F9;}.odd {background-color:#3F0;}.highlight {background-color: #ffcc00;}$("tbody tr:even").addClass("even");$("tbody tr:odd").addClass("odd");$("#theList tr").hover(function (){$(this).toggleClass("highlight");},function () {$(this).toggleClass("highlight");});需要将.highlight在css中的位置放在.even和.odd后面函数才能运行正确四、JQUERY ANIMATION SND EFFECTS1.SHOWING AND HIDING PAGE ELEMENTSshow()Display each of the set of matched elements,if they are hiddenshow(speed,callback) speed:"normal","slow","fast"Shows all matched elements using a graceful animation.Fires an optional callback after completionhide()Hides each of the set of matched elements if they are shownhide(speed,callback)Hides all matched elements using graceful animation.Fires an optional callback after completiontoggle()Toggles displaying each of the set of matched elementstoggle(switch)Toggles displaying each of the set of matched elements based upon the switch(true shows all elements,false hides all elements)toggle(speed,callback)Toggles displaying each of the set of matched elemenys using a graceful animation and firing an optional callback after completion2.FADING ELEMENTS IN AND OUTfadeIn(speed,callback)Fades in all matched elements by adjusting their opacity and firing an optional callback after completionfadeOut(speed,callback)Fades out all matched elements by adjusting their opacity to 0 and then setting display to "none" and firing an optional callback after completionfadeTo(speed,callback)Fades the opacity of all matched elements to a specified opacity and fires an optional callback after completion3.SLIDING PAGE EFFECTS speed:"slow","normal","fast",数字(毫秒为单位)slideDown(speed,callback)slideUp(speed,callback)slideToggle(speed,callback)$("#sh").slideUp(4000);4.CREATING CUSTOM ANIMATIONS animate(params,duration,easing,callback)Creates a custom animationparams:The properties on the elements to animateduration:The number of milliseconds the animation should take easing:The type of easing function to use(linear or swing) callback:The function to call when the animation is completeanimate(params,options)Creates a custom animationparams:The properties to animateoptions:Set of options for the animation to takestop()Stops all the currently running animations on all the specified elementssetInterval("rotateImages()", 2000);var oNxtPhoto = oCurPhoto.next();五、THE JQUERY UILIBRARYInteractionsDraggableDroppableResizeableSlectableSortableWidgetsAccordion $(“#accordion”).accordion(); <div id=”accordion”></div>DatepickerProgressbarDialogSliderTabsEffectsAdd ClassRemove ClassToggle ClassSwitch ClassHideShowToggleColor Animation/download 到这个网站下载各种各样的jQuery UI Library代码UI实例accordion,图片变换<link href="_css/sunny/jquery-ui-1.7.2.custom.css" rel="stylesheet" type="text/css" media="screen, projection" /><script type="text/javascript" src="_scripts/jquery-1.3.2.min.js"></script><script type="text/javascript" src="_scripts/jquery-ui-1.7.2.custom.min.js"></script><script type="text/javascript">$(function() {$("#newsSection").accordion({ header:"h4"});setInterval("rotateImages()",2000);});function rotateImages() {var oCurPhoto = $('#photoShow div.current');var oNxtPhoto = oCurPhoto.next();if(oNxtPhoto.length == 0)oNxtPhoto = $('#photoShow div:first');oCurPhoto.removeClass('current').addClass('previous');oNxtPhoto.css({ opacity: 0.0 }).addClass('current').animate({ opacity: 1.0 }, 1000, function() {oCurPhoto.removeClass('previous');});}</script>tooltip mouseover显示大图片<script type="text/javascript" src="../_scripts/jquery-1.3.2.min.js"></script><script type="text/javascript">$(function (){$("#viewlarger").hover(function() {var offset = $("#gearItem").offset();$("#tooltip1").css("top",offset.top).css("left",offset.left).css("display","block");$("#tooltip1").animate({opacity: 1.0},300);},function (){$("#tooltip1").animate({opacity: 0.0},300,function(){$("#tooltip1").css("display","none");});});});</script>selector 图片显示<script type="text/javascript" src="../_scripts/jquery-1.3.2.min.js"></script><script type="text/javascript">$(function (){$("a:has(img.gallery)").click(function() {var largePath = $(this).attr("href");var caption = $(this).attr("title");$("#photo_large").attr({src:largePath});$("#caption1").text(caption);return false;});});</script>resizable,div大小可变<link href="../_css/sunny/jquery-ui-1.7.2.custom.css" rel="stylesheet" type="text/css" media="screen, projection" /><script type="text/javascript" src="../_scripts/jquery-1.3.2.min.js"></script><script type="text/javascript" src="../_scripts/jquery-ui-1.7.2.custom.min.js"></script><script type="text/javascript">$(function() {var maxw = $("#commentsSection").width();var minw = maxw;var minh = $("#commentsSection").height();$("#commentsSection").resizable({maxWidth:maxw,minHeight:minh,minWidth:minw});});</script>。
jQuery基础教程1.jQuery主要任务。
①②③④⑤2.引用jQuery库文件的<script>标签时,必须引用在自定义脚本文件的<script>之前,否即引用不到jQuery框架。
3.$(document).ready()结构预定DOM加载完成后(不必等待图像加载完成)触发的函数调用。
4.jQuery最强大的方面之一就是它能够简化DOM遍历任务。
5.$()函数会消除使用for循环访问一组元素需求,因为放到圆括号中的任何元素都将自动执行循环遍历,并且会被保存到一个jQuery对象中。
可以在$()函数的圆括号中使用的参数几乎没有什么限制。
如:$('p')会取得文档中所有的段落<p>标识。
$('#some-id')会取得文档中具有对应的ID="some-id"的一个元素。
$('.some-class')会取得文档中带有class="some-class"类的所有元素。
6.在jQuery中,美元符号$只不过是对标识符jQuery的一种简写方式。
由于$()在JavaScript 库中很常见,所以,如果在一个页面中使用了几个这样的库,那么就会导致冲突。
在这种情况下,可以在我们自定义的jQuery代码中,通过将每个$的实例替换成jQuery来避免这种冲突。
7.jQuery支持CSS规范1到规范3中的大多数选择符,不必为哪种浏览器可能会不理解高级的选择符而担心,只要该浏览器启用了JavaScript就没有问题。
8.编写自己的程序应始终坚持渐进增强和平稳退化的理念,做到在JavaScript禁用时,页面仍然能够与启用Javascript时一样准确呈现,即使没有那么美观。
9.如CSS中定义:.horizontal{float:left;list-style:none;margin:10px;}这个horizontal类会将元素浮动到它后面元素的左侧,如果这个元素是一个列表项,那么会移除其项目符号,最后再为该元素的每一边各添加10像素的外边距。
优雅锋利的jQuery write less ,do more--By GX目录第一章基础 (4)1.1 jQuery引用 (4)1.2第一个jQuery简单代码 (4)1.3 jQuery对象和DOM对象 (4)1.4解决jQuery和其他库的冲突问题 (5)第二章选择器 (6)2.1基本选择器 (8)2.2层次选择器 (8)2.3过滤选择器 (9)2.4表单选择器 (11)2.5其他选择器 (13)第三章jQuery中的DOM操作 (13)3.1 DOM节点 (13)3.2 CSS-DOM操作 (15)第四章jQuery中的事件和动画 (16)4.1事件 (16)4.1.1加载事件 (16)4.1.2事件绑定 (16)4.1.3合成事件 (17)4.1.4事件冒泡 (18)4.1.5事件对象属性 (18)4.1.6移除事件 (19)4.1.7模拟操作 (19)4.1.8其他用法 (20)4.2动画 (21)4.2.1 show和hide方法 (21)4.2.2 fadeIn和fadeOut方法 (21)4.2.3 slideUp和slideDown方法 (21)4.2.4自定义动画animate() (21)4.2.5动画回调函数 (21)4.2.6停止动画和判断是否在动画状态 (22)4.2.7其他动画方法: (23)第五章jQuery与Ajax的应用 (24)5.1简单的Ajax (24)5.2 jQuery的Ajax (25)5.2.1 load()方法 (25)5.2.2 $.get()和$.post() (25)5.2.3 $.getScript()和$.getJson() (26)5.2.4 $.ajax() (27)5.2.5序列化元素 (28)第六章jQuery表单元素操作应用 (28)6.1 单行文本框应用 (28)6.2 多行文本框应用 (29)6.2.1高度变化 (29)6.2.2 滚动条高度变化 (30)6.3复选框应用 (30)6.4 下拉框的应用 (31)6.5 表单验证 (33)6.6表格应用 (35)6.6.1表格变色 (35)6.6.2 表格的展开关闭 (39)6.6.3 表格内容筛选 (41)6.6.4 其他应用(自行研究) (43)第七章插件(自行研究) (43)第一章基础1.1 jQuery引用和引用外部JS文件方式一样<script src="../scripts/jQuery/jQuery1.83.js" type="text/javascript"></script>不要用2.0以上版本,不支持6.0以上的IE有mini版,有完整版,有代码提示插件,自行研究1.2第一个jQuery简单代码<script src="jQuery1.8.3.js" type="text/javascript"></script><script type="text/javascript">$(document).ready(function(){alert("Hello World!");});</script>首先引入jQuery文件其次$(document).ready() 调用document对象的ready方法相当于js中的window.onload方法二者区别:$(document).ready()可以写多个window.onload只能写一个$(document).ready()在加载页面结构完毕后就执行可能DOM元素关联的东西并没有加载完window.onload待整个页面加载完毕后才执行$(document).ready(function(){ 可以简写为$(function(){ })1.3 jQuery对象和DOM对象DOM对象:var a = document.getElementById("foo")jQuery对象:$("#foo")jQuery对象是对DOM对象的封装二者不可混淆二者的方法不可通用两种对象的转换:jQuery - DOMvar $a = $("#aa");var a = $a.get(0);或者var a = $a[0];DOM - jQueryvar a = document.getElementById("foo");var $a = $(a);1.4解决jQuery和其他库的冲突问题主要问题在于对$符号的使用$符号就等同于jQuery 字符$("#d") == jQuery("#d")方法一jQuery让出$符号使用权jQuery.noConflict();方法二jQuery自定义快捷方式var $j = jQuery.noConflict(); 此时$j就等同于$方法三jQuery局部使用$jQuery.noConflict();jQuery(function($){ $("#s").css('font-size','80px')});方法四jQuery外部包裹声明jQuery.noConflict();(function($){ $(function(){ }) })方法五先引入jQuery无需jQuery.noConflict();语句,直接使用jQuery代替$第二章选择器测试用页面代码:<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "/TR/xhtml1/DTD/xhtml1-transitional.dtd"><html xmlns="/1999/xhtml"><head><meta http-equiv="Content-Type" content="text/html; charset=utf-8" /><title>选择器</title><style type="text/css">div,span,p{width:140px;height:140px;margin:5px;background:#aaa;border:#000 1px solid;float:left;font-size:17px;font-family:Verdana;}div.mini{width:55px;height:55px;background:#aaa;font-size:12px;}div.hide{display:none;}</style></head><script src="jQuery1.8.3.js" type="text/javascript"></script><script src="Class2.js" type="text/javascript"></script><body><div class="one" id="one">id是one class也是one的div<div class="mini">class为mini</div></div><div class="one" id="two" title="test">id是two class是one title是test 的div<div class="mini" title="other">class 是mini title是other的div</div> <div class="mini" title="test">class 是mini title是test的div</div></div><div class="one"><div class="mini">class是mini的div</div><div class="mini">class是mini的div</div><div class="mini">class是mini的div</div><div class="mini"></div></div><div class="one"><div class="mini">class是mini的div</div><div class="mini">class是mini的div</div><div class="mini">class是mini的div</div><div class="mini" title="tesst">class是mini title是tesst</div></div><div style="display:none;" class="none">style的display属性是none的div</div><div class="hide">class是hide的div</div><div>包含input 的type属性为hidden的div<input type="hidden" size="8" /></div><span id="mover">正在执行动画的span元素</span><h1>基本过滤选择器</h1><br><input type="text" value="获取焦点"></body></html>(检验是否获取到jQuery对象时应该用$(“#d”).length>0 来判断)2.1基本选择器$(function(){$('#one').css('background','#bbffaa');$('.mini').css('background','#bbffaa');$('div').css('background','red');$('*').css('background','blue');$('span,#two').css('background','red');});2.2层次选择器1.后代元素:$(…div span‟) 选取div里的所有span(包括子元素里的span 孙元素里的span)2.子元素:$(…div >span‟) 选取div里下一层子元素里的span元素(只包括子元素里的span)3.相邻元素:$(….one+div‟) 选取class为one的相邻的下一个元素可用$(….one‟).next(…div‟)代替4.同辈元素:$(…#two~div‟) 选取id为two的元素后面所有的同辈div元素可用$(…#two‟).nextall(…div‟)代替2.3过滤选择器1.基本过滤:first $(…div:first‟) 选取所有div元素中的第一个div元素:last $(…div:last‟ ) 选取所有div元素中的最后一个div元素:not() $(…input:not(.myclass)‟) 选取class不是myclass的input元素:even $(…table tr:even‟) 选取表格中的偶数行下标从0开始0也是偶数:odd $(…table tr:odd‟) 选取表格中的奇数行下标从0开始:ep() $(…table tr td:eq(2)‟) 选取表格中每一行的第三列括号内的下标从0开始:gt() $(…table tr td:gt(1)‟) 选取表格中每一行第二列以后的列不包括第二列:lt() $(…table tr td:gt(3)‟) 选取表格中每一行第四列之前的列不包括第四列:header $(…:header‟) 选取网页中所有标题元素<h1>等:animated $(…div:animated‟) 选取正在执行动画的div元素:focus $(…:focus‟) 选取当前获取焦点的元素2.内容过滤:contains() $(“div:contains(…我‟)”)选取文本含有“我”的div:empty $(…div:empty‟) 选取不含子元素(包括文本)的div:has() $(…div:has(p)‟) 选取含有p元素的div:parent $(…div:parent‟) 选取拥有子元素(包含文本)的div3.可见性过滤:hidden $(…:hidden‟) 选择所有不可见元素包括隐藏域display:none visibility:hidden(display:none完全隐藏,页面不存在该区域visibility:hidden不显示,页面还有这块区域,只是不显示内容) :visible $(…div:visible‟) 选取所有可见div4.属性过滤[] $(…div[id]‟) 选取拥有id属性的div[=] $(…div[title=test]‟) 选取title属性为test的div[!=] $(…div[title!=test]‟) 选取title属性不为test的div 没有title属性的div也被选取[^=] $(…div[title^=test]‟) 选取title属性以test开始的div[$=] $(…div[title$=test]‟) 选取title属性以test结束的div[*=] $(…div[title*=test]‟) 选取title属性包含test的div[|=] $(…div[title|=test]‟) 选取title等于test或者以test为前缀的div[~=] $(…div[title~=test]‟) 选取title用空格分隔的值中包含test字符的元素[][][] $(…div[id][title=test]‟) 选取有id属性且title属性值为test的div5.子元素过滤:nth-child(index/even/odd/qpuation) $(…table tr td:nth-child(2)‟) 选取每个tr下第二个td 注意子元素下标从1开始:first-child $(…ul li:first-child‟) 选取每个ul中第一个li:last-child $(…ul li:last-child‟) 选取每个ul中最后一个li:only-child $(…ul li:only-child‟) 如果ul下只有li一个子元素,那么该元素被选中6.表单对象属性过滤测试页面代码:<form id="form1" action="###">可用元素:<input name="add" value="可用文本框" type="text" /><br>不可用元素:<input name="email" disabled="disabled" value="不可用文本框" type="text" /><br>可用元素:<input name="che" value="可用文本框" type="text" /><br>不可用元素:<input name="name" disabled="disabled" value="不可用文本框" type="text" /><br><br>多选框:<br><input type="checkbox" name="newletter" checked="checked" value="test1"/>test1<input type="checkbox" name="newletter" value="test2"/>test2<input type="checkbox" name="newletter" value="test3"/>test3<input type="checkbox" name="newletter" checked="checked" value="test4"/>test4<input type="checkbox" name="newletter" value="test5"/>test5<div></div><br/><br/>下拉列表1:<br><select name="test" multiple="multiple" style="height:100px"><option>浙江</option><option selected="selected">湖南</option><option>北京</option><option selected="selected">天津</option><option>广州</option><option>湖北</option></select><br/><br/>下拉列表2:<br><select name="test2" class="test2"><option>浙江</option><option>湖南</option><option selected="selected">北京</option><option>天津</option><option>广州</option><option>湖北</option></select><br/><br/></form>:enabled $(…#form1 :enabled‟) 选取id为form1的表单内所有可用元素:disabled $(…#form1 :disabled‟) 选取id为form1的表单内所有不可用元素:checked $(…input:checked‟) 选取所有被选中的input元素:selected $(“select option:selected”) 选取下拉框中所有被选中的元素2.4表单选择器测试页面代码:<form id="form1" action="###"><input type="button" value="Button" /><br /><input type="checkbox" name="c"/>1<input type="checkbox" name="c"/>2<input type="checkbox" name="c"/>3<br><input type="file" /><br><input type="hidden"/><div style="display:none">test</div><br /><input type="image" /><br><input type="password" /><br /><input type="radio" name="a" />1<input type="radio" name="a" />2<br /><input type="reset" /><br /><input type="submit" value="提交"/><br /><input type="text" /><br /><select><option>option</option></select><br /><textarea></textarea><br /><button>Button</button><br /></form>:input $(…:input‟) 选取所有input textarea select button 元素:text $(…:text‟) 选取所有单行文本框元素:password $(“:password”) 选取所有密码框:radio $(…:radion‟) 选取所有单选框:checkbox $(“:checkbox”) 选取所有复选框:submit $(…:submit‟) 选取所有提交按钮:image $(“:image”) 选取所有图像按钮:reset $(…:reset‟) 选取所有重置按钮:button $(…:button‟) 选取所有按钮:file $(…:file‟) 选取所有上传域:hidden $(…:hidden‟) 选取所有不可见元素,包括隐藏域disply:none visibility:hidden注意选择器里面的空格问题:$(….test :hidden‟) 选取的是class为test的元素里面的所有隐藏元素$(….test:hidden‟) 选取的是class为test的元素2.5其他选择器通过扩展jQuery插件可以使用更多选择器,请自行研究。
JQuery入门学习笔记一、jQuery简介:1、常用的JavaScript库及缺点:(1)Prototype库:结构松散。
(2)Dojo:API不稳定。
(3)ExtJs:本身比较臃肿,且收费。
2、jQuery的优势:(1)轻量库。
(2)强大的选择器。
(3)出色的DOM操作封装。
(4)可靠的事件处理机制。
(5)完善的Ajax。
(6)出色地浏览器兼容性。
3、jQuery对象和DOM对象:(1)jQuery对象:jQuery对象是一个数值对象,它不同于JavaScript中的对象。
常用[index]或者jQuery 中自带get(index)方法来得到指定元素。
常用以下方法定义一个jQuery对象。
var $element_name=$("#id")/*查找指定id名的元素,返回一个集合*/varelement_id=$element_name[0];varelement_id=$element_name.get(index);(2)DOM对象:DOM对象类同于jQuery对象,可以通过以下方法将DOM对象转换成jQuery对象。
对于一个DOM对象,只需要用$()把DOM对象包装起来就可以获得一个jQuery对象了。
varcr=document.getElementById("cr");var $cr=$(cr); /*使用$()方法将DOM对象转换成jQuery对象*/二、jQuery选择器:jQuery选择器分为基本选择器、层次选择器、过滤选择器和表单选择器1、基本选择器:基本选择器根据元素的id、类名class、元素名称等进行选择,选择返回的一般都是集合元素。
选择器描述返回示例#id 根据给定的id匹配一个元素单个元素$("#test")选取id为test的元素.class 根据给定的类名匹配元素集合元素$(".test")选取所有class为test的元素Element 根据给定的元素名匹配元素集合元素$("p")选取所有的<p>元素* 匹配所有的元素集合元素$("*")选取所有元素Selector1,selector 将每个选择器匹配到的元素合并后返回集合元素2、层次选择器:层次选择器用来选择元素的后代元素、子元素、相邻元素和兄弟元素等。
一、JQuery对象和DOM(文本对象模型)对象定义1)变量定义的区别var $mObject=JQuery对象;var m=DOM对象;2)JQuery对象和DOM对象转化1、JQuery对象转化为DOM对象通过[index]和get(index)两种方法可以将JQuery对象转化为DOM对象。
方法一:1var$cr=$("cr"); //JQuery对象2var cr=$cr[0]; //DOM对象方法二:var$cr=$("cr"); //JQuery对象var cr=$cr.get(0); //DOM对象2、DOM对象转化为JQuery对象var cr=doucment.getElementById("cr"); //DOM对象var$cr=$(cr); //JQuery对象二、JQuery获取页面上的元素3)$与JQueryJQuery为了防止和其它的库有冲突,只建立了一个对象就是jQuery对象,$是jQuery 的缩写形式。
因此:$.ajax和jQuery.ajax是等价的。
4)JQuery的$()简介JQuery为了达到document.getElementById(“myID”)的目的,采用$(“#myID”)实现。
得到ID为myID的元素。
$(“div p”) :得到所有<div>标签下的<p>元素$(“div.container”) :得到class为container的<div>元素$(“div #msg”) :得到<div>标签下面id为msg的元素$(“table a”,context) :得到context为上下文的table里面的所有链接元素。
<input name=”username” type=”text” value=”vinisn”/> →$(”username”)<input id=”passwd” type=”password” value=”” /> →$(“#passwd”)<input type=”text” class=”inputcss” value=”” /> →$(“.inputcss”)<a rel=”nofollow self” href=”example.html”>some text </a>→$(“[a@rel=’ nofollow self’]”)$(“a[@rel]”) :选择所有的以<a>为标记并且具有rel属性的元素。
$(“input[name=myname]”) :选择所有的input标签并且标签的名字为myname $(“input[name!=myname]”) :选择所有的input并且标签名字不为myname$("div > p").html() :值为div下的p元素中的内容还可以根据正则表达式来选择。
注意:$("p")和$("#p")的区别,$("p")表示取所有p标签(<p></p>)的元素,$("#p")表示取id 为"p"(<span id="p"></span>)的元素.5)下面根据正则表达式来选择,以什么结尾$(“a[herf$=index.htm]”) :选择所有的<a>标签并且这个标签具有以index.htm结尾的href 属性。
6)根据正则表达式来选择,包含什么$(“a[herf*=]”) : 选择所有的<a>标签并且这个标签的href属性值包含7)根据属性选择$("span[id='Unit_" + m_id + "']").html("万元");可以使用变量表示控件的属性值8)自定义选择符$(“tr:odd”) :取得表格中的奇数行$(“tr:even”) :取得表格中的偶数行$(“div.horizontal:eq(1)”) :选择带有horizontal类的div集合中的第2项$(‘td:contains(“Henry”)’) :”选择表格中包含“Henry”内容的单元格。
$("#orderedlist li:last") : list的最后一个element上生效alert($("p").get(1).innerHTML); :alert对话框显示第二个<p>标签的内容注意get和eq的区别,eq返回的是jQuery对象,get返回的是所匹配的dom对象,所有取$("p").eq(1)对象的内容用jQuery方法html(),而取$("p").get(1)的内容用innerHTML9)访问某个元素Var myTag=$(“#myelement”).get(0).tagName:找到Id=” myelement”的元素的第0个元素的标签名。
var f = $("div");alert($(f).find("p").html()) :显示div中的p内容alert($("img").length); :弹出alert对话框显示2,表示找到两个匹配对象10)add(expr) 在原对象的基础上在附加符合指定表达式的jquery对象<p>Hello</p><p><span>Hello Again</span></p><a href="#" onClick="jq()">jQuery</a>jQuery代码及功能:function jq(){var f=$("p").add("span");for(var i=0;i < $(f).size();i++){alert($(f).eq(i).html());}}执行$("p")得到匹配<p>的对象,有两个,add("span")是在("p")的基础上加上匹配<span >的对象,所有一共有3个,从上面的函数运行结果可以看到$("p").add("span")是3个对象的集合,分别是[<p>Hello</p>],[<p><span>Hello Again</span></p>],[<span>Hello Again</span>]。
add(el) 在匹配对象的基础上在附加指定的dom元素。
$("p").add(document.getElementById("a"));add(els) 在匹配对象的基础上在附加指定的一组对象,els是一个数组。
<p>Hello</p><p><span>Hello Again</span></p>jQuery代码及功能:function jq(){var f=$("p").add([document.getElementById("a"), document.getElemen tById("b")])for(var i=0;i < $(f).size();i++){alert($(f).eq(i).html());}}注意els是一个数组,这里的[ ]不能漏掉。
11)匹配结点的父节点ancestors () 一依次以匹配结点的父节点的内容为对象,根节点除外(有点不好理解,看看下面例子就明白了)<div><p>one</p><span><u>two</u></span>jQuery代码及功能:function jq(){var f= $("u").ancestors();for(var i=0;i < $(f).size();i++){alert($(f).eq(i).html());}}第一个对象是以<u>的父节点的内容为对象,[ <u>two</u> ]第一个对象是以<u>的父节点的父节点(div)的内容为对象,[<p>one</p><span><u>two</u></span> ]一般一个文档还有<body>和<html>,依次类推下去。
ancestors (expr) 在ancestors()的基础上之取符合表达式的对象如上各例子讲var f改为var f= $("u").ancestors(“div”),则只返回一个对象:[ <p>one</p><span><u>two</u></span> ]children() 返回匹配对象的子节点<p>one</p><div id="ch"><span>two</span></div>jQuery代码及功能:function jq(){alert($("#ch").children().html());}$("#ch").children()得到对象[ <span>two</span> ].所以.html()的结果是”two”children(expr) 返回匹配对象的子介点中符合表达式的节点<div id="ch"><span>two</span><span id="sp">three</span></div>jQuery代码及功能function jq(){alert($("#ch").children(“#sp”).html());}$("#ch").children()得到对象[<span>two</span><span id="sp">three</span> ].$("#ch").children(“#sp”)过滤得到[<span id="sp">three</span> ]parent () parent (expr)取匹配对象父节点的。