当前位置: 移动技术网 > IT编程>开发语言>JavaScript > JavaScript开发中了解了这些才能开始发挥jQuery的威力

JavaScript开发中了解了这些才能开始发挥jQuery的威力

2018年12月09日  | 移动技术网IT编程  | 我要评论

由于当前jquery如此的如雷贯耳,相信不用介绍什么是jquery了,公司代码中广泛应用了jquery,但我在看一些小朋友的代码时发现一个问题,小朋友们使用的仅仅是jquery的皮毛,只是使用id选择器与attr方法,还有几个动画,如果只是如此,相比于其带来的开销,其实还不如不使用,下面介绍几个jquery常用的方法,来让jquery的威力发挥出来,否则只用有限的几个方法,相对于运行速度问题,真不如不用jquery。

jquery如此之好用,和其在获取对象时使用与css选择器兼容的语法有很大关系,毕竟css选择器大家都很熟悉(关于css选择器可以看看十分钟搞定css选择器),但其强大在兼容了css3的选择器,甚至多出了很多。

选择器

有了css选择器基础后,看jquery的选择器就很简单了,不再详细一一说明

 

基本选择器  
$(‘*') 匹配页面所有元素
$(‘#id') id选择器
$(‘.class') 类选择器
$(‘element') 标签选择器
   
组合/层次选择器  
$(‘e,f') 多元素选择器,用”,分隔,同时匹配元素e或元素f
$(‘e f') 后代选择器,用空格分隔,匹配e元素所有的后代(不只是子元素、子元素向下递归)元素f
$(e>f) 子元素选择器,用”>”分隔,匹配e元素的所有直接子元素
$(‘e+f') 直接相邻选择器,匹配e元素之后相邻同级元素f
$(‘e~f') 普通相邻选择器(弟弟选择器),匹配e元素之后同级元素f(无论直接相邻与否)
$(‘.class1.class2') 匹配类名中既包含class1又包含class2的元素
基本过滤选择器  
$("e:first") 所有e中的第一个
$("e:last") 所有e中的最后一个
$("e:not(selector)") 按照selector过滤e
$("e:even")             所有e中index是偶数
$("e:odd")              所有e中index是奇数
$("e:eq(n)")           所有e中index为n的元素
$("e:gt(n)")           所有e中index大于n的元素
$("e:ll(n)")            所有e中index小于n的元素
$(":header") 选择h1~h7 元素
$("p:animated") 选择正在执行动画效果的元素
内容过滤器  
$(‘e:contains(value)') 内容中包含value值的元素
$(‘e:empty') 内容为空的元素
$(‘e:has(f)') 子元素中有f的元素,$(‘p:has(a)'):包含a标签的p
$(‘e: parent') 父元素是e的元素,$(‘td: parent'):父元素是td的元素
可视化选择器  
$(‘e:hidden') 所有被隐藏的e
$(‘e:visible') 所有可见的e
属性过滤选择器  
$(‘e[attr]') 含有属性attr的e
$(‘e[attr=value]') 属性attr=value的e
$(‘e[attr !=value]') 属性attr!=value的e
$(‘e[attr ^=value]') 属性attr以value开头的e
$(‘e[attr $=value]') 属性attr以value结尾的e
$(‘e[attr *=value]') 属性attr包含value的e
$(‘e[attr][attr *=value]') 可以连用
子元素过滤器  
$(‘e:nth-child(n)') e的第n个子节点
$(‘e:nth-child(3n+1)') e的index符合3n+1表达式的子节点
$(‘e:nth-child(even)') e的index为偶数的子节点
$(‘e:nth-child(odd)') e的index为奇数的子节点
$(‘e:first-clild') 所有e的第一个子节点
$(‘e:last-clild') 所有e的最后一个子节点
$(‘e:only-clild') 只有唯一子节点的e的子节点
表单元素选择器  
$(‘e:type') 特定类型的input
$(‘:checked') 被选中的checkbox或radio
$(‘option: selected') 被选中的option

筛选方法

 

.find(selector) 查找集合每个元素的子节点

get the descendants(子节点) of each element in the current set of matched elements, filtered by a selector, jquery object, or element.

 

. 代码如下:

$('li.item-ii').find('li').css('background-color', 'red');

 

.filter(selector) 过滤当前集合内元素

reduce(减少) the set of matched elements to those that match the selector or pass the function's test.

 

. 代码如下:

$('li').filter(':even').css('background-color', 'red');

 

基本方法

.ready(handler) 文档加载完成后执行的方法,区别于window.onload

specify a function to execute when the dom is fully loaded.

 

. 代码如下:


$(document).ready(function() {
  // handler for .ready() called.
});

 

.each(function(index,element)) 遍历集合内每个元素

iterate over a jquery object, executing a function for each matched element.

 

. 代码如下:


$("li" ).each(function( index ) {
  console.log( index + ": " + $(this).text() );
});

 

jquery.extend( target [, object1 ] [, objectn ] ) 合并对象

merge the contents of two or more objects together into the first object.

 

. 代码如下:

var object = $.extend({}, object1, object2);

 

获取元素

.eq(index) 按index获取jquery对象集合中的某个特定jquery对象

reduce the set of matched elements to the one at the specified index.

.eq(-index) 按逆序index获取jquery对象集合中的某个特定jquery对象

an integer indicating the position of the element, counting backwards from the last element in the set.

 

. 代码如下:

$( "li" ).eq( 2 ).css( "background-color", "red" );


 

 

.get(index) 获取jquery集合对象中某个特定index的dom对象(将jquery对象自动转换为dom对象)

retrieve one of the dom elements matched by the jquery object.

 

. 代码如下:

console.log( $( "li" ).get( -1 ) );

 

.get() 将jquery集合对象转换为dom集合对象并返回

retrieve the dom elements matched by the jquery object.

 

. 代码如下:

console.log( $( "li" ).get() );



.index() / .index(selector)/ .index(element) 从给定集合中查找特定元素index

 

search for a given element from among the matched elements.

1. 没参数返回第一个元素index

2.如果参数是dom对象或者jquery对象,则返回参数在集合中的index

3.如果参数是选择器,返回第一个匹配元素index,没有找到返回-1

 

. 代码如下:


var listitem = $( "#bar" );
alert( "index: " + $( "li" ).index( listitem ) );

 

.clone([withdataandevents][,deepwithdataandevents]) 创建jquery集合的一份deep copy(子元素也会被复制),默认不copy对象的shuju和绑定事件

create a deep copy of the set of matched elements.

 

. 代码如下:

$( ".hello" ).clone().appendto( ".goodbye" );

 

.parent([selector]) 获取jquery对象符合selector的父元素

get the parent of each element in the current set of matched elements, optionally filtered by a selector.

 

. 代码如下:

$( "li.item-a" ).parent('ul').css( "background-color", "red" );

 

.parents([selector]) 获取jquery对象符合选择器的祖先元素

get the ancestors of each element in the current set of matched elements, optionally filtered by a selector.

 

. 代码如下:

$( "span.selected" ) .parents( "p" ) .css( "border", "2px red solid" )

 

插入元素

.append(content[,content]) / .append(function(index,html)) 向对象尾部追加内容

insert content, specified by the parameter, to the end of each element in the set of matched elements.

1. 可以一次添加多个内容,内容可以是dom对象、html string、 jquery对象

2. 如果参数是function,function可以返回dom对象、html string、 jquery对象,参数是集合中的元素位置与原来的html值

 

. 代码如下:


$( ".inner" ).append( "<p>test</p>" );
$( "body" ).append( $newp1, [ newp2, existingp1 ] );
$( "p" ).append( "<strong>hello</strong>" );
$( "p" ).append( $( "strong" ) );
$( "p" ).append( document.createtextnode( "hello" ) );

 

.appendto(target) 把对象插入到目标元素尾部,目标元素可以是selector, dom对象, html string, 元素集合,jquery对象;

insert every element in the set of matched elements to the end of the target.

 

. 代码如下:


$( "h2" ).appendto( $( ".container" ) );
$( "<p>test</p>" ).appendto( ".inner" );

 

.prepend(content[,content]) / .prepend(function(index,html)) 向对象头部追加内容,用法和append类似

insert content, specified by the parameter, to the beginning of each element in the set of matched elements.

 

. 代码如下:

$( ".inner" ).prepend( "<p>test</p>" );

 

.prependto(target) 把对象插入到目标元素头部,用法和prepend类似

insert every element in the set of matched elements to the beginning of the target.

 

. 代码如下:

$( "<p>test</p>" ).prependto( ".inner" );

 

.before([content][,content]) / .before(function) 在对象前面(不是头部,而是外面,和对象并列同级)插入内容,参数和append类似

insert content, specified by the parameter, before each element in the set of matched elements.

 

. 代码如下:


$( ".inner" ).before( "<p>test</p>" );
$( ".container" ).before( $( "h2" ) );
$( "p" ).first().before( newp1, [ newp2, existingp1 ] );
$( "p" ).before( "<b>hello</b>" );
$( "p" ).before( document.createtextnode( "hello" ) );

 

.insertbefore(target) 把对象插入到target之前(同样不是头部,是同级)

insert every element in the set of matched elements before the target.

 

. 代码如下:

$( "h2" ).insertbefore( $( ".container" ) );

 

.after([content][,content]) / .after(function(index)) 和before相反,在对象后面(不是尾部,而是外面,和对象并列同级)插入内容,参数和append类似

insert content, specified by the parameter, after each element in the set of matched elements.

 

. 代码如下:


$( ".inner" ).after( "<p>test</p>" );
$( "p" ).after( document.createtextnode( "hello" ) );

 

.insertafter(target) 和insertbefore相反,把对象插入到target之后(同样不是尾部,是同级)

insert every element in the set of matched elements after the target.

 

. 代码如下:


$( "<p>test</p>" ).insertafter( ".inner" );
$( "p" ).insertafter( "#foo" );

 

包裹元素

.wrap(wrappingelement) / .wrap(function(index)) 为每个对象包裹一层html结构,可以是selector, element, html string, jquery object

wrap an html structure around each element in the set of matched elements.

 

. 代码如下:


<p class="container">
  <p class="inner">hello</p>
  <p class="inner">goodbye</p>
</p>$( ".inner" ).wrap( "<p class='new'></p>" );
<p class="container">
  <p class="new">
    <p class="inner">hello</p>
  </p>
  <p class="new">
    <p class="inner">goodbye</p>
  </p>
</p>

 

.wrapall(wrappingelement) 把所有匹配对象包裹在同一个html结构中

wrap an html structure around all elements in the set of matched elements.

 

. 代码如下:


<p class="container">
  <p class="inner">hello</p>
  <p class="inner">goodbye</p>
</p>$( ".inner" ).wrapall( "<p class='new' />");<p class="container">
  <p class="new">
    <p class="inner">hello</p>
    <p class="inner">goodbye</p>
  </p>
</p>

 

.wrapinner(wrappingelement) / .wrapinner(function(index)) 包裹匹配元素内容,这个不好说,一看例子就懂

wrap an html structure around the content of each element in the set of matched elements.

 

. 代码如下:


<p class="container">
  <p class="inner">hello</p>
  <p class="inner">goodbye</p>
</p>$( ".inner" ).wrapinner( "<p class='new'></p>");
<p class="container">
  <p class="inner">
    <p class="new">hello</p>
  </p>
  <p class="inner">
    <p class="new">goodbye</p>
  </p>
</p>

 

.unwap() 把dom元素的parent移除

remove the parents of the set of matched elements from the dom, leaving the matched elements in their place.

 

. 代码如下:

ptags = $( "p" ).unwrap();

 

属性方法

.val() 获取元素的value值

get the current value of the first element in the set of matched elements.

 

. 代码如下:


$( "input:checkbox:checked" ).val();

 

.val(value) /.val(function(index,value)) 为元素设置值,index和value同样是指在为集合中每个元素设置的时候该元素的index和原value值

set the value of each element in the set of matched elements.

 

. 代码如下:


$( "input" ).val( ‘hello' );
$( "input" ).on( "blur", function() {
  $( this ).val(function( i, val ) {
    return val.touppercase();
  });
});

 

.attr(attributename) 获取元素特定属性的值

get the value of an attribute for the first element in the set of matched elements.

 

. 代码如下:


var title = $( "em" ).attr( "title" );

 

.attr(attributename,value) / .attr(attributesjson) / .attr( attributename, function(index, attr) ) 为元素属性赋值

set one or more attributes for the set of matched elements.

 

. 代码如下:


$( "#greatphoto" ).attr( "alt", "beijing brush seller" );

 

$( "#greatphoto" ).attr({
  alt: "beijing brush seller",
  title: "photo by kelly clark"
});

$( "#greatphoto" ).attr( "title", function( i, val ) {
  return val + " - photo by kelly clark";
});

 

.prop( propertyname ) 获取元素某特性值

get the value of a property for the first element in the set of matched elements.

 

. 代码如下:


$( elem ).prop( "checked" )

 

.prop(propertyname,value) / .prop(propertiesjson) / .prop(propertyname,function(index,oldpropertyvalue)) 为元素特性赋值

set one or more properties for the set of matched elements.

 

. 代码如下:


$( "input" ).prop( "checked", true );

 

$( "input[type='checkbox']" ).prop( "checked", function( i, val ) {
  return !val;
});

$( "input[type='checkbox']" ).prop({
  disabled: true
});

 

关于attribute 和 property区别可以看看 jquery的attr与prop


.data(key,value) / .value(json) 为html dom元素添加数据,html5元素 已有data-*属性

store arbitrary data associated with the matched elements.the .data() method allows us to attach data of any type to dom elements in a way that is safe from circular references and therefore from memory leaks.

 

. 代码如下:


$( "body" ).data( "foo", 52 );
$( "body" ).data( "bar", { mytype: "test", count: 40 } );
$( "body" ).data( { baz: [ 1, 2, 3 ] } );

 

.data(key) / .data() 获取获取data设置的数据或者html5 data-*属性中的数据

return the value at the named data store for the first element in the jquery collection, as set by data(name, value) or by an html5 data-* attribute.

 

. 代码如下:


alert( $( "body" ).data( "foo" ) );
alert( $( "body" ).data() );

 

alert( $( "body" ).data( "foo" ) ); // undefined
$( "body" ).data( "bar", "foobar" );
alert( $( "body" ).data( "bar" ) ); // foobar

 

css方法
.hasclass(calssname) 检查元素是否包含某个class,返回true/false

determine whether any of the matched elements are assigned the given class.

 

. 代码如下:

$( "#myp" ).hasclass( "foo" )

 

.addclass(classname) / .addclass(function(index,currentclass)) 为元素添加class,不是覆盖原class,是追加,也不会检查重复

adds the specified class(es) to each of the set of matched elements.

 

. 代码如下:


$( "p" ).addclass( "myclass yourclass" );

 

$( "ul li" ).addclass(function( index ) {
  return "item-" + index;
});

 

removeclass([classname]) / ,removeclass(function(index,class)) 移除元素单个/多个/所有class

remove a single class, multiple classes, or all classes from each element in the set of matched elements.

 

. 代码如下:


$( "p" ).removeclass( "myclass yourclass" );
$( "li:last" ).removeclass(function() {
  return $( this ).prev().attr( "class" );
});

 

.toggleclass(classname) /.toggleclass(classname,switch) /  .toggleclass([switch]) / .toggleclass( function(index, class, switch) [, switch ] ) toggle是切换的意思,方法用于切换,switch是个bool类型值,这个看例子就明白

add or remove one or more classes from each element in the set of matched elements, depending on either the class's presence or the value of the switch argument.

<p class="tumble">some text.</p>

第一次执行

. 代码如下:


$( "p.tumble" ).toggleclass( "bounce" )
<p class="tumble bounce">some text.</p>


第二次执行

 

 

. 代码如下:


$( "p.tumble" ).toggleclass( "bounce" )
<p class="tumble">some text.</p>

 

 

. 代码如下:


$( "#foo" ).toggleclass( classname, addorremove );

 

// 两种写法意思一样

if ( addorremove ) {
  $( "#foo" ).addclass( classname );
} else {
  $( "#foo" ).removeclass( classname );
}

 

 

. 代码如下:


$( "p.foo" ).toggleclass(function() {
  if ( $( this ).parent().is( ".bar" ) ) {
    return "happy";
  } else {
    return "sad";
  }
});

 

.css(propertyname) / .css(propertynames) 获取元素style特定property的值

get the value of style properties for the first element in the set of matched elements.

 

. 代码如下:


var color = $( this ).css( "background-color" );

 

 var styleprops = $( this ).css([
    "width", "height", "color", "background-color"
  ]);

 

.css(propertyname,value) / .css( propertyname, function(index, value) ) / .css( propertiesjson ) 设置元素style特定property的值

set one or more css properties for the set of matched elements.

 

. 代码如下:


$( "p.example" ).css( "width", function( index ) {
  return index * 50;
});

 

$( this ).css( "width", "+=200" );


$( this ).css( "background-color", "yellow" );

   $( this ).css({
      "background-color": "yellow",
      "font-weight": "bolder"
    });

 

事件方法

.bind( eventtype [, eventdata ], handler(eventobject) ) 绑定事件处理程序,这个经常用,不多解释

attach a handler to an event for the elements.

 

. 代码如下:


$( "#foo" ).bind( "click", function() {
  alert( "user clicked on 'foo.'" );
});

 

.delegate( selector, eventtype, handler(eventobject) ) 这个看官方解释吧

attach a handler to one or more events for all elements that match the selector, now or in the future, based on a specific set of root elements.

 

. 代码如下:


$( "table" ).on( "click", "td", function() {//这样把td的click事件处理程序绑在table上
  $( this ).toggleclass( "chosen" );
});

 

.on( events [, selector ] [, data ], handler(eventobject) ) 1.7后推荐使用,取代bind、live、delegate

attach an event handler function for one or more events to the selected elements.

 

. 代码如下:


$( "#datatable tbody" ).on( "click", "tr", function() {
  alert( $( this ).text() );
});

 

关于bind、live、delegate、on的区别可以看看 jquery三种事件绑定方式.bind(),.live(),.delegate()

.trigger( eventtype [, extraparameters ] ) javascript出发元素绑定事件

execute all handlers and behaviors attached to the matched elements for the given event type.

 

. 代码如下:


$( "#foo" ).trigger( "click" );

 

.toggle( [duration ] [, complete ] ) / .toggle( options ) 隐藏或显示元素

display or hide the matched elements.

 

. 代码如下:


$( ".target" ).toggle();$( "#clickme" ).click(function() {
  $( "#book" ).toggle( "slow", function() {
    // animation complete.
  });
});

 

动画/ajax
这两部分内容比较多,不是简单的一个function就可以的,这里只是列举一下常用方法名,关于其使用可以看看 jquery api animation ajax ,或者 jquery的动画处理总结,asp.net 使用ajax动画

queue/dequeue/clearqueue

delay/stop

fadein/fadeout/fadeto/fadetoggle

slideup/slidedown/slidetoggle

show/hide

ajax

$.ajax

$.load

$.get

最后

了解了上面这些内容,使用jquery进行web开发的时候就可以体验到jquery的威力了。本文不是jquery学习指南,仅仅是个常用方法介绍,如果大家想学习jquery,最好的教材还是jquery api,本文中示例与英文解释全部来源于jquery api。 另外文中介绍内容远远不是jquery全部,但是首先掌握了这些可以对jquery有一个比较全面的认识,然后再学习其他内容的时候就可以游刃有余了。

如对本文有疑问, 点击进行留言回复!!

相关文章:

验证码:
移动技术网