你想知道的do{...}while(0)的作用,都在这里了

我们在嵌入式开发的过程中,经常可以碰到在一些宏定义或者是代码段中使用了do {...} while(0)的语句,从语义上理解,do {...} while(0)内的逻辑就只执行一次,并没有循环执行,粗略看来,似乎画蛇添足了,那么为什么还需要在只执行一次的逻辑外面加上一层do {...} while(0)语句呢?实际上,在这些逻辑中使用do {...} while(0)的作用远大于美化你的代码,下面就来看看实际的使用场景。


1、用于定义一个作用域,避免替换的时候出错

我们都知道,在程序中如果一些常量参数或者代码语句反复出现,就可以使用宏定义来替代。预处理阶段,对程序中所有出现的“宏名”,预处理器都会用宏定义中的字符串替代,这称为“宏替换”或“宏展开”。

这样做可提高程序的通用性和易读性,减少不一致性,一个较好的宏名可以更好的让读者理解常量参数的含义;同时程序易于修改,我们仅需要改变一个宏定义,就可以改变整个程序中出现的所有该常量或者语句。

但是有时可能程序代码段中,出现多条语句重复连续的使用,这样我们就可以尝试使用一个复杂的宏来替换。你有可能会这样定义:

1#define REPLACE_FUN() funA(); funB()

  本意是在程序中当出现funA()和funB()多条语句连续使用时,使用REPLACE_FUN()来替换。

1if(判断条件)
2     REPLACE_FUN();
        但是实际上在预处理的时候,宏展开替换后变成了:
1if(判断条件)
2   funA();
3 funB();   //此处funB()一定会执行,造成逻辑错误

可以看出,funB()不会按照判断条件才去执行。而是变成了一条独立的语句,而如果在宏中使用括号:

1#define REPLACE_FUN() {funA(); funB();}

我们一般的代码习惯都会在语句的末尾加上分号,因此也会出错:

1if(判断条件)
2    REPLACE_FUN();
3//宏展开后为:4if(判断条件)
5{
6    funA();
7    funB();
8 };    //此处替换后多一个分号;导致编译报错

因此,针对这种多条重复语句的连续使用,如果想用宏替换实现这个作用域的功能,就可以考虑使用do {...} while(0)语句:

 1define REPLACE_FUN() \
 2do{ \
 3            funA();\
 4            funB();\
 5           }while(0)\
 6//宏展开前为:          7if(判断条件)
 8    REPLACE_FUN();
 9//宏展开后为:10if(判断条件)
11do{
12          funA();
13          funB();
14      }while(0);    //根据判断条件,正确执行了一次逻辑

2、避免goto语句的使用

goto语句也称为无条件转移语句,使用后可以从多重循环或者多个判断中直接跳出。对于如下例子:

 1void fun(int a)
 2{
 3if(1 == a)
 4   {
 5        ...//todo 6goto exit;
 7   }  
 8if(2 == a)
 9   {
10      ...//todo11goto exit;
12   }
13exit:
14    ...//todo15    printf("a is error"\n);
16 }

但是为了程序结构的清晰,还是要尽量限制goto语句的使用,我们可以使用do {...} while(0)结构配合break跳出单层的循环的方法来替代这种goto的用法。

 1int fun(int a)
 2{
 3do{
 4if(1 == a)
 5       {
 6          ...//todo 7break;
 8       }  
 9if(2 == a)
10       {
11          ...//todo12break;
13       }
14    }while(0);
15    ...//todo16    printf("a is error"\n);
17 }


3、定义一个单独的函数块来实现复杂的操作

当某个函数程序功能较为复杂,在该函数的代码段中如果不再单独定义一个函数实现部分逻辑,可以使用do {...} while(0)作为一个代码块,将想要实现的逻辑放在do {...} while(0)中,同时在该在do {...} while(0)代码块中定义的变量,可以不用考虑和函数之前或者之后的变量名重复冲突的问题。但是为了代码的易读性,还是尽量声明不同的变量名。

 1int a;
 2char b;
 3int func()
 4{
 5int a = 3;
 6char b = 5;
 7do{
 8int a;
 9char b;
10         ......//todo11     }while(0);    
12 }

4、避免空宏的警告

有的时候,程序为了不同的平台移植或者不同架构的限制,很多时候会先定义空宏,后续再根据实际的需要看是否定义具体内容。但是在编译的时候,这些空宏可能会给出warning,为了避免这样的warning,我们可以使用do{...}while(0)来定义空宏,这种情况不太常见,因为有很多编译器已经支持空宏。

1//空宏2#define EMPTY_FUN
3//增加do{...}while(0)来定义空宏4#define EMPTY_FUN do{}while(0) //避免了可能的编译warning

  • 4
    点赞
  • 17
    收藏
    觉得还不错? 一键收藏
  • 1
    评论
计算机基础程序设计复习题 一、单项选择题 1. 计算机的基本组成部分包括中央处理器、存储器、输出设备和( ) A. 键盘 B. 鼠标 C. 显示器 D. 输入设备 2. 下列属于计算机病毒特征的是( ) A. 模糊性 B. 高速性 C. 传染性 D. 危急性 3. C#程序的( )方法被称为程序的大门,应用程序从这里开始运行。 A. Main() B. Begin() C. Start() D. main() 4. 可用作C#程序用户标识符的一组标识符是( ) A. void define +WORD B. a3_b3_345YN C. for –abe Case D. 2A.do sizeof 5. 下列代码输出的结果是( ) int i=0;i=++i+8; Console.WriteLine(i++); A. 8 B. 9 C. 10 D. 11 6. 以下类型中,不属于值类型的是( ) A. 数值类型 B. 布尔类型 C.字符类型 D. 类类型 7. 设"int a=12;",则执行完语句"a+=a*a;"后,a的值是( ) A. 12 B. 144 C. 156 D. 288 8. 下列关于switch的语法结构的描述不正确的是( ) A.switch条件判断接收int、char、string三种类型 B.switch的case块,必须要加上break子句 C.switch的case块,可以没有break D.switch的default块,在条件都不满足的情况下执行 9. 有定义语句: int[,]a=new int[5,6]; 则下列正确的数组元素的引用是( ) A. a(3,4) B. a(3)(4) C. a[3][4] D. a[3,4] 10. 在C#语言的循环结构中,首先执行一次,然后再判断条件的循环结构是( ) A. while循环 B. do…while循环 C. for循环 D. foreach循环 11. 为了避免嵌套的条件分支语句if…else…的二义性,C语言规定:C程序中的else总是与( )组成配对关系。 A. 缩排位置相同的if B. 在其之前未配对的if C. 在其之前未配对的最近的if D. 同一行上的if 12. 让控件不可见的属性是( ) A. Cursor B. Enabled C. Dock D. Visible 13. DateTime类的( )属性可以获得系统的当前日期和时间。 A. Now B. Today C. Tomorrow D. ThisTime 14. 以下语句中,不正确的有( ) A. int[] a; B. int a[]=new int[2,3]; C. int[]a={1,3}; D. int a=new int[]{1,3}; 15.文本框控件的( )属性用来设置其是否是只读的。 A. ReadOnly B. Locked C. Lock D. Style 16. 在ADO.NET中,( )用来从数据源中获取只读的数据。 A. DataSet B. Command C. DataReader D. DataAdapter 17. 软件生命周期中花费时间最多的阶段是( ) A. 软件定义 B. 软件开发 C. 软件测试 D. 软件运行维护 18. 在ADO.NET中,下列关于DataSet对象的说法有误的是( ) A. 可以向DataSet的表集合中添加新表 B. DataSet中的数据发生改变之后,它会自动更新数据库中对应的数据 C. DataSet就好像是内存中的一个"临时数据库" D. 对DataSet中的数据可以执行读写操作 19. 程序流程图、N-S图和PAD图是( )使用的表达工具。 A. 设计阶段的概要设计 B. 设计阶段的详细设计 C. 编码阶段 D. 测试阶段 20. 在软件编码阶段,下列做法不宜采用的是( ) A. 使用标准的控制结构 B. 尽可能使用库函数 C. 程序编写先考虑清晰性 D. 尽量使用GOTO语句 21. 下列选项中内聚性最强的是( ) A. 顺序内聚 B. 过程内聚 C. 逻辑内聚 D. 功能内聚 22. 结构化设计方法定义了一些不同的映射,利用这些映射可以实现( ) A. 从数据结构导出程序结构 B. 从模块结构导出程序结构 C. 从模块结构导出数据结构 D. 从数据流图导出软件结构图 23. 在C#中,若要将磁盘中的文件删除,应使用File类的( ) A. Copy B. Delete C. Move D. Create 24. 在C#中,基本的文件操作是由( )命名空间提供的类来实现的。 A. System.Data B. System.Configuration C. System.Collections
codeceo 首页问答热门文章RSS订阅 文章首页 Java JavaScript PHP iOS Android HTML5 CSS3 Linux C++ Python C# Node.Js 一文让你彻底理解 Java HashMap 和 ConcurrentHashMap 2018-07-25 分类:JAVA开发、编程开发、首页精华0人评论 来源:crossoverjie.top 分享到:更多0 前言 Map 这样的 Key Value 在软件开发中是非常经典的结构,常用于在内存中存放数据。 本篇主要讨论 ConcurrentHashMap 这样一个并发容器,在正式开始之前我觉得有必要谈谈 HashMap,没有它就不会有后面的 ConcurrentHashMap。 HashMap 众所周知 HashMap 底层是基于 数组 + 链表 组成的,不过在 jdk1.7 和 1.8 中具体实现稍有不同。 Base 1.7 1.7 中的数据结构图: 先来看看 1.7 中的实现。 这是 HashMap 中比较核心的几个成员变量;看看分别是什么意思? 初始化桶大小,因为底层是数组,所以这是数组默认的大小。 桶最大值。 默认的负载因子(0.75) table 真正存放数据的数组。 Map 存放数量的大小。 桶大小,可在初始化时显式指定。 负载因子,可在初始化时显式指定。 重点解释下负载因子: 由于给定的 HashMap 的容量大小是固定的,比如默认初始化: public HashMap() { this(DEFAULT_INITIAL_CAPACITY, DEFAULT_LOAD_FACTOR); } public HashMap(int initialCapacity, float loadFactor) { if (initialCapacity < 0) throw new IllegalArgumentException("Illegal initial capacity: " + initialCapacity); if (initialCapacity > MAXIMUM_CAPACITY) initialCapacity = MAXIMUM_CAPACITY; if (loadFactor <= 0 || Float.isNaN(loadFactor)) throw new IllegalArgumentException("Illegal load factor: " + loadFactor); this.loadFactor = loadFactor; threshold = initialCapacity; init(); } 给定的默认容量为 16,负载因子为 0.75。Map 在使用过程中不断的往里面存放数据,当数量达到了 16 * 0.75 = 12 就需要将当前 16 的容量进行扩容,而扩容这个过程涉及到 rehash、复制数据等操作,所以非常消耗性能。 因此通常建议能提前预估 HashMap 的大小最好,尽量的减少扩容带来的性能损耗。 根据代码可以看到其实真正存放数据的是 transient Entry<K,V>[] table = (Entry<K,V>[]) EMPTY_TABLE; 这个数组,那么它又是如何定义的呢? Entry 是 HashMap 中的一个内部类,从他的成员变量很容易看出: key 就是写入时的键。 value 自然就是值。 开始的时候就提到 HashMap 是由数组和链表组成,所以这个 next 就是用于实现链表结构。 hash 存放的是当前 key 的 hashcode。 知晓了基本结构,那来看看其中重要的写入、获取函数: put 方法 public V put(K key, V value) { if (table == EMPTY_TABLE) { inflateTable(threshold); } if (key == null) return putForNullKey(value); int hash = hash(key); int i = indexFor(hash, table.length); for (Entry<K,V> e = table[i]; e != null; e = e.next) { Object k; if (e.hash == hash && ((k = e.key) == key || key.equals(k))) { V oldValue = e.value; e.value = value; e.recordAccess(this); return oldValue; } } modCount++; addEntry(hash, key, value, i); return null; } 判断当前数组是否需要初始化。 如果 key 为空,则 put 一个空值进去。 根据 key 计算出 hashcode。 根据计算出的 hashcode 定位出所在桶。 如果桶是一个链表则需要遍历判断里面的 hashcode、key 是否和传入 key 相等,如果相等则进行覆盖,并返回原来的值。 如果桶是空的,说明当前位置没有数据存入;新增一个 Entry 对象写入当前位置。 void addEntry(int hash, K key, V value, int bucketIndex) { if ((size >= threshold) && (null != table[bucketIndex])) { resize(2 * table.length); hash = (null != key) ? hash(key) : 0; bucketIndex = indexFor(hash, table.length); } createEntry(hash, key, value, bucketIndex); } void createEntry(int hash, K key, V value, int bucketIndex) { Entry<K,V> e = table[bucketIndex]; table[bucketIndex] = new Entry<>(hash, key, value, e); size++; } 当调用 addEntry 写入 Entry 时需要判断是否需要扩容。 如果需要就进行两倍扩充,并将当前的 key 重新 hash 并定位。 而在 createEntry 中会将当前位置的桶传入到新建的桶中,如果当前桶有值就会在位置形成链表。 get 方法 再来看看 get 函数: public V get(Object key) { if (key == null) return getForNullKey(); Entry<K,V> entry = getEntry(key); return null == entry ? null : entry.getValue(); } final Entry<K,V> getEntry(Object key) { if (size == 0) { return null; } int hash = (key == null) ? 0 : hash(key); for (Entry<K,V> e = table[indexFor(hash, table.length)]; e != null; e = e.next) { Object k; if (e.hash == hash && ((k = e.key) == key || (key != null && key.equals(k)))) return e; } return null; } 首先也是根据 key 计算出 hashcode,然后定位到具体的桶中。 判断该位置是否为链表。 不是链表就根据 key、key 的 hashcode 是否相等来返回值。 为链表则需要遍历直到 key 及 hashcode 相等时候就返回值。 啥都没取到就直接返回 null 。 Base 1.8 不知道 1.7 的实现大家看出需要优化的点没有? 其实一个很明显的地方就是: 当 Hash 冲突严重时,在桶上形成的链表会变的越来越长,这样在查询时的效率就会越来越低;时间复杂度为 O(N)。 因此 1.8 中重点优化了这个查询效率。 1.8 HashMap 结构图: 先来看看几个核心的成员变量: static final int DEFAULT_INITIAL_CAPACITY = 1 << 4; // aka 16 /** * The maximum capacity, used if a higher value is implicitly specified * by either of the constructors with arguments. * MUST be a power of two <= 1<<30. */ static final int MAXIMUM_CAPACITY = 1 << 30; /** * The load factor used when none specified in constructor. */ static final float DEFAULT_LOAD_FACTOR = 0.75f; static final int TREEIFY_THRESHOLD = 8; transient Node<K,V>[] table; /** * Holds cached entrySet(). Note that AbstractMap fields are used * for keySet() and values(). */ transient Set<Map.Entry<K,V>> entrySet; /** * The number of key-value mappings contained in this map. */ transient int size; 和 1.7 大体上都差不多,还是有几个重要的区别: TREEIFY_THRESHOLD 用于判断是否需要将链表转换为红黑树的阈值。 HashEntry 修改为 Node。 Node 的核心组成其实也是和 1.7 中的 HashEntry 一样,存放的都是 key value hashcode next 等数据。 再来看看核心方法。 put 方法 看似要比 1.7 的复杂,我们一步步拆解: 判断当前桶是否为空,空的就需要初始化(resize 中会判断是否进行初始化)。 根据当前 key 的 hashcode 定位到具体的桶中并判断是否为空,为空表明没有 Hash 冲突就直接在当前位置创建一个新桶即可。 如果当前桶有值( Hash 冲突),那么就要比较当前桶中的 key、key 的 hashcode 与写入的 key 是否相等,相等就赋值给 e,在第 8 步的时候会统一进行赋值及返回。 如果当前桶为红黑树,那就要按照红黑树的方式写入数据。 如果是个链表,就需要将当前的 key、value 封装成一个新节点写入到当前桶的后面(形成链表)。 接着判断当前链表的大小是否大于预设的阈值,大于时就要转换为红黑树。 如果在遍历过程中找到 key 相同时直接退出遍历。 如果 e != null 就相当于存在相同的 key,那就需要将值覆盖。 最后判断是否需要进行扩容。 get 方法 public V get(Object key) { Node<K,V> e; return (e = getNode(hash(key), key)) == null ? null : e.value; } final Node<K,V> getNode(int hash, Object key) { Node<K,V>[] tab; Node<K,V> first, e; int n; K k; if ((tab = table) != null && (n = tab.length) > 0 && (first = tab[(n - 1) & hash]) != null) { if (first.hash == hash && // always check first node ((k = first.key) == key || (key != null && key.equals(k)))) return first; if ((e = first.next) != null) { if (first instanceof TreeNode) return ((TreeNode<K,V>)first).getTreeNode(hash, key); do { if (e.hash == hash && ((k = e.key) == key || (key != null && key.equals(k)))) return e; } while ((e = e.next) != null); } } return null; } get 方法看起来就要简单许多了。 首先将 key hash 之后取得所定位的桶。 如果桶为空则直接返回 null 。 否则判断桶的第一个位置(有可能是链表、红黑树)的 key 是否为查询的 key,是就直接返回 value。 如果第一个不匹配,则判断它的下一个是红黑树还是链表。 红黑树就按照树的查找方式返回值。 不然就按照链表的方式遍历匹配返回值。 从这两个核心方法(get/put)可以看出 1.8 中对大链表做了优化,修改为红黑树之后查询效率直接提高到了 O(logn)。 但是 HashMap 原有的问题也都存在,比如在并发场景下使用时容易出现死循环。 final HashMap<String, String> map = new HashMap<String, String>(); for (int i = 0; i < 1000; i++) { new Thread(new Runnable() { @Override public void run() { map.put(UUID.randomUUID().toString(), ""); } }).start(); } 但是为什么呢?简单分析下。 看过上文的还记得在 HashMap 扩容的时候会调用 resize() 方法,就是这里的并发操作容易在一个桶上形成环形链表;这样当获取一个不存在的 key 时,计算出的 index 正好是环形链表的下标就会出现死循环。 如下图: 遍历方式 还有一个值得注意的是 HashMap 的遍历方式,通常有以下几种: Iterator<Map.Entry<String, Integer>> entryIterator = map.entrySet().iterator(); while (entryIterator.hasNext()) { Map.Entry<String, Integer> next = entryIterator.next(); System.out.println("key=" + next.getKey() + " value=" + next.getValue()); } Iterator<String> iterator = map.keySet().iterator(); while (iterator.hasNext()){ String key = iterator.next(); System.out.println("key=" + key + " value=" + map.get(key)); } 强烈建议使用第一种 EntrySet 进行遍历。 第一种可以把 key value 同时取出,第二种还得需要通过 key 取一次 value,效率较低。 简单总结下 HashMap:无论是 1.7 还是 1.8 其实都能看出 JDK 没有对它做任何的同步操作,所以并发会出问题,甚至 1.7 中出现死循环导致系统不可用(1.8 已经修复死循环问题)。 因此 JDK 推出了专项专用的 ConcurrentHashMap ,该类位于 java.util.concurrent 包下,专门用于解决并发问题。 坚持看到这里的朋友算是已经把 ConcurrentHashMap 的基础已经打牢了,下面正式开始分析。 ConcurrentHashMap ConcurrentHashMap 同样也分为 1.7 、1.8 版,两者在实现上略有不同。 Base 1.7 先来看看 1.7 的实现,下面是他的结构图: 如图所示,是由 Segment 数组、HashEntry 组成,和 HashMap 一样,仍然是数组加链表。 它的核心成员变量: /** * Segment 数组,存放数据时首先需要定位到具体的 Segment 中。 */ final Segment<K,V>[] segments; transient Set<K> keySet; transient Set<Map.Entry<K,V>> entrySet; Segment 是 ConcurrentHashMap 的一个内部类,主要的组成如下: static final class Segment<K,V> extends ReentrantLock implements Serializable { private static final long serialVersionUID = 2249069246763182397L; // 和 HashMap 中的 HashEntry 作用一样,真正存放数据的桶 transient volatile HashEntry<K,V>[] table; transient int count; transient int modCount; transient int threshold; final float loadFactor; } 看看其中 HashEntry 的组成: 和 HashMap 非常类似,唯一的区别就是其中的核心数据如 value ,以及链表都是 Volatile 修饰的,保证了获取时的可见性。 原理上来说:ConcurrentHashMap 采用了分段锁技术,其中 Segment 继承于 ReentrantLock。不会像 HashTable 那样不管是 put 还是 get 操作都需要做同步处理,理论上 ConcurrentHashMap 支持 CurrencyLevel (Segment 数组数量)的线程并发。每当一个线程占用锁访问一个 Segment 时,不会影响到其他的 Segment。 下面也来看看核心的 put get 方法。 put 方法 public V put(K key, V value) { Segment<K,V> s; if (value == null) throw new NullPointerException(); int hash = hash(key); int j = (hash >>> segmentShift) & segmentMask; if ((s = (Segment<K,V>)UNSAFE.getObject // nonvolatile; recheck (segments, (j << SSHIFT) + SBASE)) == null) // in ensureSegment s = ensureSegment(j); return s.put(key, hash, value, false); } 首先是通过 key 定位到 Segment,之后在对应的 Segment 中进行具体的 put。 final V put(K key, int hash, V value, boolean onlyIfAbsent) { HashEntry<K,V> node = tryLock() ? null : scanAndLockForPut(key, hash, value); V oldValue; try { HashEntry<K,V>[] tab = table; int index = (tab.length - 1) & hash; HashEntry<K,V> first = entryAt(tab, index); for (HashEntry<K,V> e = first;;) { if (e != null) { K k; if ((k = e.key) == key || (e.hash == hash && key.equals(k))) { oldValue = e.value; if (!onlyIfAbsent) { e.value = value; ++modCount; } break; } e = e.next; } else { if (node != null) node.setNext(first); else node = new HashEntry<K,V>(hash, key, value, first); int c = count + 1; if (c > threshold && tab.length < MAXIMUM_CAPACITY) rehash(node); else setEntryAt(tab, index, node); ++modCount; count = c; oldValue = null; break; } } } finally { unlock(); } return oldValue; } 虽然 HashEntry 中的 value 是用 volatile 关键词修饰的,但是并不能保证并发的原子性,所以 put 操作时仍然需要加锁处理。 首先第一步的时候会尝试获取锁,如果获取失败肯定就有其他线程存在竞争,则利用 scanAndLockForPut() 自旋获取锁。 尝试自旋获取锁。 如果重试的次数达到了 MAX_SCAN_RETRIES 则改为阻塞锁获取,保证能获取成功。 再结合图看看 put 的流程。 将当前 Segment 中的 table 通过 key 的 hashcode 定位到 HashEntry。 遍历该 HashEntry,如果不为空则判断传入的 key 和当前遍历的 key 是否相等,相等则覆盖旧的 value。 不为空则需要新建一个 HashEntry 并加入到 Segment 中,同时会先判断是否需要扩容。 最后会解除在 1 中所获取当前 Segment 的锁。 get 方法 public V get(Object key) { Segment<K,V> s; // manually integrate access methods to reduce overhead HashEntry<K,V>[] tab; int h = hash(key); long u = (((h >>> segmentShift) & segmentMask) << SSHIFT) + SBASE; if ((s = (Segment<K,V>)UNSAFE.getObjectVolatile(segments, u)) != null && (tab = s.table) != null) { for (HashEntry<K,V> e = (HashEntry<K,V>) UNSAFE.getObjectVolatile (tab, ((long)(((tab.length - 1) & h)) << TSHIFT) + TBASE); e != null; e = e.next) { K k; if ((k = e.key) == key || (e.hash == h && key.equals(k))) return e.value; } } return null; } get 逻辑比较简单: 只需要将 Key 通过 Hash 之后定位到具体的 Segment ,再通过一次 Hash 定位到具体的元素上。 由于 HashEntry 中的 value 属性是用 volatile 关键词修饰的,保证了内存可见性,所以每次获取时都是最新值。 ConcurrentHashMap 的 get 方法是非常高效的,因为整个过程都不需要加锁。 Base 1.8 1.7 已经解决了并发问题,并且能支持 N 个 Segment 这么多次数的并发,但依然存在 HashMap 在 1.7 版本中的问题。 那就是查询遍历链表效率太低。 因此 1.8 做了一些数据结构上的调整。 首先来看下底层的组成结构: 看起来是不是和 1.8 HashMap 结构类似? 其中抛弃了原有的 Segment 分段锁,而采用了 CAS + synchronized 来保证并发安全性。 也将 1.7 中存放数据的 HashEntry 改为 Node,但作用都是相同的。 其中的 val next 都用了 volatile 修饰,保证了可见性。 put 方法 重点来看看 put 函数: 根据 key 计算出 hashcode 。 判断是否需要进行初始化。 f 即为当前 key 定位出的 Node,如果为空表示当前位置可以写入数据,利用 CAS 尝试写入,失败则自旋保证成功。 如果当前位置的 hashcode == MOVED == -1,则需要进行扩容。 如果都不满足,则利用 synchronized 锁写入数据。 如果数量大于 TREEIFY_THRESHOLD 则要转换为红黑树。 get 方法 根据计算出来的 hashcode 寻址,如果就在桶上那么直接返回值。 如果是红黑树那就按照树的方式获取值。 就不满足那就按照链表的方式遍历获取值。 1.8 在 1.7 的数据结构上做了大的改动,采用红黑树之后可以保证查询效率(O(logn)),甚至取消了 ReentrantLock 改为了 synchronized,这样可以看出在新版的 JDK 中对 synchronized 优化是很到位的。 总结 看完了整个 HashMap 和 ConcurrentHashMap 在 1.7 和 1.8 中不同的实现方式相信大家对他们的理解应该会更加到位。 其实这块也是面试的重点内容,通常的套路是: 谈谈你理解的 HashMap,讲讲其中的 get put 过程。 1.8 做了什么优化? 是线程安全的嘛? 不安全会导致哪些问题? 如何解决?有没有线程安全的并发容器? ConcurrentHashMap 是如何实现的? 1.7、1.8 实现有何不同?为什么这么做? 这一串问题相信大家仔细看完都能怼回面试官。 除了面试会问到之外平时的应用其实也蛮多,像之前谈到的 Guava 中 Cache 的实现就是利用 ConcurrentHashMap 的思。 同时也能学习 JDK 作者大牛们的优化思路以及并发解决方案。 其实写这篇的前提是源于 GitHub 上的一个 Issues,也希望大家能参与进来,共同维护好这个项目。 分享到:更多0 继续浏览有关ConcurrentHashmapHashMapJAVA开发的文章 发表我的评论 表情插代码发布评论有人回复时邮件通知我 热门文章 成为伟大程序员的 10 个要点 如何成为一名成功的程序员 25个最基本的JavaScript面试问题及答案 程序员最核心的竞争力是什么? Java 内存模型 JMM 浅析 理解 Flexbox:你需要知道的一切 创造型职业程序员的无奈 我(作为一名开发者)所犯过的错误 黑客老王:一个人的黑客史 阿里面试回来,Java程序员谈一谈 职场人生 软件工程师生存指南:面试准备、工作经验和实用工具 自由职业的这两年 倾听程序员的心声真的很重要 平庸开发者的生存指南 为什么我从 Google 辞职而为自己工作 我是一名朝九晚五的程序员(你也可以!) 成为伟大程序员的 10 个要点 如何处理前任程序员留下的代码 开发人员爱开发 如何成为一名成功的程序员 版权所有,保留一切权利! © 2016 码农网 浙ICP备14003773号-1 浙公网安备 33010502000955号 商务合作QQ:290074886(请注明来意)
数据库系统概论实验报告 专业 班级 组别 指导教师 姓名 同组人 实验时间 2020 年 4 月 15 日 实验地点 K7-405 实验名称 程序设计基础 实验目的 1. 熟悉 VFP 命令文件的建立和执行。 2. 掌握结构化程序设计的一般方法。 3. 熟练掌握条件语句和循环语句的使用。 实验仪器: 1、支持 Intel Core 3.0G 及其以上 CPU,内存 1G 以上、硬盘 1T 以上容量的微 机; 软件配有 Windows7 操作系统及 Visual Foxpro8.0 软件。 2、了解 Visual Foxpro8.0 软件的特点及系统组成,在电脑上操作 VFP8.0 软件。 实验内容、步骤及程序: 1. 编写程序,判断输入的年份是否是闰年(建议用 IF 语句实现,输入用交互式 语句,输出用?命令) 。 提示:闰年是能被 4 整除但不能被 100 整除,或能被 400 整除。 2. 编写程序,判断输入的字符是字母、数字或是特殊符号(建议用 DO CASE 语 句实现,输入和输出用格式化语句) 。 提示:本程序中判断的数字是字符型数字,与数值型数字类型不同。 3.编写程序, 显示学生登记表中入校总分在 550 分以上的学生记录 (建议用 DO WHILE 语句实现) 。 4. 编写程序,实现验证密码正确后浏览学生登记表的内容,密码设为"OK" ,最多 只能输入三次,密码错误或输入超过三次给出提示(建议用 FOR 循环语句) 。 提示:本程序中因为输入的密码不能在屏幕上显示,所以在输入语句前后要下列两 条语句: SET CONSOLE OFF 输入语句的内容不显示在屏幕上 SET CONSOLE ON 恢 复输入语句内容的屏幕显示另外, 需要提示输入信息的语句应放在 SET CONSOLE OFF 语句之前, 否则提示信息不会显示, 最好是将输入提示语句和输入语句用两条语句, 分别放在 SET CONSOLE OFF 的前后。 左上方框里填写学号后两位,学习委员按此顺号(报告展开排序)交给老师 5. 编写程序,统计学生登记表中男、女生的人数(建议用 SCAN 循环语句) 。 6. 编写程序,统计学生登记表中男、女生的人数(建议用 SCAN 循环语句) 。 3. 编写程序,根据输入的姓名,计算学生的平均成绩,并显示成绩等级。 提示: 等级计算如下: 90<=平均成绩<=100 优 80<=平均成绩<=90 良 70<=平均成绩<=80 中 60<=平均成绩<=70 及格 平均成绩<=60 不及格 由于姓名和成绩要涉及到学生登记表和学生成绩表, 需要分别在两个工作区打 开两个表, 根据输入的姓名,从学生登记表中取得相对应的学号,再根据学号在学生成绩表 中计算出平均成绩,通过等级的计算方法,计算出学生成绩的等级,最后输入学 生的平均分和成绩等级。 7. 编写程序,能根据输入的姓名,查找并显示学生各门课程的成绩,要求能反复 查找。 提示: 为了实现反复查找的功能,在这里需要用一个循环语句和是否退出循环语 句来控制: ANS="Y" DO WHILE .T. …… WAIT "是否继续查找(Y/N)?" TO ANS IF UPPER(ANS)="Y" LOOP ELSE EXIT ENDIF ENDDO 此程序也涉及到两个表的操作,具体过程参照上题。 此程序要用两个循环,外循环见 。内循环用于显示对应于一个学号的多门课程 成绩的 循环显示。 8.编写程序,对任意输入的 10 个数,按从小到大的顺序进行排列(要求输出排序 前后的数据) 。 提示: 要定义一个一维数组,用于存放输入的 10 个数据 用两个 FOR 循环分别输出排序前后的数据。 排序要用到 FOR 循环的嵌套,其中需要用到一个中间变量进行两个数据的交换。 实验小结: 通过本次实验, 我了解了 VFP 命令文件的建立和执行, 以及结构化程序设计的一般 方法,掌握了条件语句和循环语句的使用。 教师评语: 1. 实验结果及解释: ( 准确合理、 较准确、 不合理 ) ;占 30% 2. 实验步骤的完整度: ( 完整、 中等、 不完整 ) ;占 30% 3. 实验程序的正确性: ( 很好、 较好、 中等、 较差、 很差 ) ;占 30% 4. 卷面整洁度: ( 很好、 较好、 中等、 较差、 很差 ) ;占 10% 评定等级: ( ) 教师签名: 日期:
程序设计实例 本章介绍了循环程序设计方法,讲述了两种循环程序,三种循环语句。包括前两章 讲述的顺序程序结构、分支程序结构在内,这些控制结构内的语句部分都允许任意形式 的语句。这些控制结构之间可以互相嵌套,而且这种嵌套没有层次限制。比如,if语句 内可以包含循环语句,循环语句内又可以继续包含if 语句,等等。 又比如,一个循环语句内可以含有循环语句,内层循环语句内还可以再包含循环语句, 形成所谓的多重循环,等等。 【例4.12】编程序,输出如下序列的前 50 项。该序列的第一项为 0 ; 第二项为 1 ; 以后的奇数项为其前两项之和;偶数项为其前两项之差。 解1:该问题应该一项一项的生成,生成一项输出一项。在生成一项时要考虑该项是 偶数项还是奇数项;生成并输出一项后,为生成下一项做准备,应该把后边的项向前串 。得如下图4.30的PAD图。程序如下。 #include "stdio.h" void main( ) { int u,v,w,k ; u=0 ; v=1 ; printf ( "%5d\n%5d\n",u,v); k=3 ; do { if ( k%2 == 0 ) w=v-u; else w=v+u; printf ( "%12d\n",w); u=v ; v=w ; k=k+1 ; }while ( k<=50 ) ; } 解2:该问题生成一项时,可以不用分支判断,而采用标志单元的方法,这种方法在 程序设计中是经常使用的。用这种方法PAD图如图4.31。程序如下。 #include "stdio.h" void main( ) { int u,v,w,k ; int flag; u=0 ; v=1 ; printf ( "%5d\n%5d\n",u,v); k=3 ; flag = -1 ; do } w = v + flag*u; flag = -flag ; printf ( "%5d\n",w); u=v ; v=w ; k=k+1 ; }while ( k<=50 ) ; } 【例4.13】编程序,输入两个正整数u 、v ,采用欧几里德辗转相除算法求它们的最大公因数并输出。 解:欧几里德辗转相除算法求u 、v最大公因数的计算过程是: u % v R1 v % R1 R2 R1 % R2 R3 R2 % R3 R4 … … … … … … … … Rn-1 % Rn Rn+1=0 到此余数Rn+1为"0",计算过程结束。Rn 为正整数u 、v的最大公因数。此计算过程用PAD描述成图4.32。编出程序如下。 #include "stdio.h" void main( ) { int u,v,r ; printf("pleace input u 、v:"); scanf("%d%d",&u,%v); r=v ; while ( r!=0 ) { r = u%v ; u = v ; v = r ; } printf ( "gcd(u,v) = %5d\n"u ); } 【例4.14】编程序,输入正整数N,计算r1!+r2!+...+rn! 并输出。其中,N=r1r2...rn 。 解:该程序是一个计算若干数据项之和的程序。本章已经编写过多个求和的程序, 现在总结一下求和程序模式。所有计算和的程序都使用一个和单元,有类似图4.33的模 式。这里用后判断条件的循环,当然也可以采用先判断条件的循环。其中: S是和单元; 开始进入循环之前和单元S必须清"0"; 在循环体内,每循环一次给和单元加上一项; 最后循环结束,和单元中的值即为所求之和。 具体落实到本题,求和算法如图4.34的PAD所示。 下边求精图4.32中的计算r!。阶乘是一个连乘积。 r! = 1 * 2 * 3 * … * r 所有计算连乘积的程序都使用一个积单元,有类似图4.35的程序模式。这里用后判 断条件的 循环,当然也可以采用先判断条件的循环。其中: P是积单元; 开始进入循环之前积单元P必须置"1"; 在循环体内,每循环一次向积单元乘入一项; 最后循环结束,积单元中的值即为所求之积。 具体落实到本问题计算r!,得如图4.36的PAD。 综合图4.34和图4.36得图4.37的最终算法PAD。程序如下: #include "stdio.h" void main( ) { int N,S,P,u,r ; printf("pleace input N:"); scanf("%d",&N); S=0 ; while ( N!=0 ) { r = N%10 ; N = N/10 ; P=1; u=1; while ( u<=r ) { P=P*u ; u=u+1 ; } S=S+P; } printf ( "r1!+r2!+...+rn! = %5d\n"S )
jQuery1.2 API 中文版折叠展开折叠全部展开全部 英文说明 核心jQuery 核心函数 jQuery(expression,[context]) jQuery(expression,[context]) 这个函数接收一个包含 CSS 选择器的字符串,然后用这个字符串去匹配一组元素。 jQuery 的核心功能都是通过这个函数实现的。 jQuery中的一切都构建于这个函数之上,或者说都是在以某种方式使用这个函数。这个函数最基本的用法就是向它传递一个表达式(通常由 CSS 选择器组成),然后根据这个表达式来查找所有匹配的元素。 默认情况下, 如果没有指定context参数,$()将在当前的 HTML 文档中查找 DOM 元素;如果指定了 context 参数,如一个 DOM 元素集或 jQuery 对象,那就会在这个 context 中查找。 参考 Selectors 获取更多用于 expression 参数的 CSS 语法的信息。 -------------------------------------------------------------------------------- This function accepts a string containing a CSS selector which is then used to match a set of elements. The core functionality of jQuery centers around this function. Everything in jQuery is based upon this, or uses this in some way. The most basic use of this function is to pass in an expression (usually consisting of CSS), which then finds all matching elements. By default, if no context is specified, $() looks for DOM elements within the context of the current HTML document. If you do specify a context, such as a DOM element or jQuery object, the expression will be matched against the contents of that context. See Selectors for the allowed CSS syntax for expressions. 返回值 jQuery 参数 expression (String) : 用来查找的字符串 context (Element, jQuery) : (可选) 作为待查找的 DOM 元素集、文档或 jQuery 对象。 示例 找到所有 p 元素,并且这些元素都必须是 div 元素的子元素。 HTML 代码: <p>one</p> <div><p>two</p></div> <p>three</p> jQuery 代码: $("div > p"); 结果: [ <p>two</p> ] -------------------------------------------------------------------------------- 在文档的第一个表单中,查找所有的单选按钮(即: type 值为 radio 的 input 元素)。 jQuery 代码: $("input:radio", document.forms[0]); -------------------------------------------------------------------------------- 在一个由 AJAX 返回的 XML 文档中,查找所有的 div 元素。 jQuery 代码: $("div", xml.responseXML); jQuery(html)jQuery(html) 根据提供的原始 HTML 标记字符串,动态创建由 jQuery 对象包装的 DOM 元素。 你可以传递一个手写的 HTML 字符串,或者由某些模板引擎或插件创建的字符串,也可以是通过 AJAX 加载过来的字符串。但是在你创建 input 元素的时会有限制,可以参考第二个示例。当然这个字符串可以包含斜杠 (比如一个图像地址),还有反斜杠。当你创建单个元素时,请使用闭合标签或 XHTML 格式。例如,创建一个 span ,可以用 $("<span/>") 或 $("<span></span>") ,但不推荐 $("<span>") -------------------------------------------------------------------------------- Create DOM elements on-the-fly from the provided String of raw HTML. You can pass in plain HTML Strings written by hand, create them using some template engine or plugin, or load them via AJAX. There are limitations when creating input elements, see the second example. Also when passing strings that may include slashes (such as an image path), escape the slashes. When creating single elements use the closing tag or XHTML format. For example, to create a span use $("<span/>") or $("<span></span>") instead of without the closing slash/tag. 返回值 jQuery 参数 html (String) : 用于动态创建DOM元素的HTML标记字符串 示例 动态创建一个 div 元素(以及其中的所有内容),并将它追加到 body 元素中。在这个函数的内部,是通过临时创建一个元素,并将这个元素的 innerHTML 属性设置为给定的标记字符串,来实现标记到 DOM 元素转换的。所以,这个函数既有灵活性,也有局限性。 jQuery 代码: $("<div><p>Hello</p></div>").appendTo("body"); -------------------------------------------------------------------------------- 创建一个 <input> 元素必须同时设定 type 属性。因为微软规定 <input> 元素的 type 只能写一次。 jQuery 代码: // 在 IE 中无效: $("<input>").attr("type", "checkbox"); // 在 IE 中有效: $("<input type='checkbox'>"); jQuery(elements)jQuery(elements) 将一个或多个DOM元素转化为jQuery对象。 这个函数也可以接收XML文档和Window对象(虽然它们不是DOM元素)作为有效的参数。 -------------------------------------------------------------------------------- Wrap jQuery functionality around a single or multiple DOM Element(s). This function also accepts XML Documents and Window objects as valid arguments (even though they are not DOM Elements). 返回值 jQuery 参数 elements (Element, Array<Element>) : 用于封装成jQuery对象的DOM元素 示例 设置页面背景色。 jQuery 代码: $(document.body).css( "background", "black" ); -------------------------------------------------------------------------------- 隐藏一个表单中所有元素。 jQuery 代码: $(myForm.elements).hide() jQuery(callback)jQuery(callback) $(document).ready()的简写。 允许你绑定一个在DOM文档载入完成后执行的函数。这个函数的作用如同$(document).ready()一样,只不过用这个函数时,需要把页面中所有需要在 DOM 加载完成时执行的$()操作符都包装到其中来。从技术上来说,这个函数是可链接的--但真正以这种方式链接的情况并不多。 你可以在一个页面中使用任意多个$(document).ready事件。 参考 ready(Function) 获取更多 ready 事件的信息。 -------------------------------------------------------------------------------- A shorthand for $(document).ready(). Allows you to bind a function to be executed when the DOM document has finished loading. This function behaves just like $(document).ready(), in that it should be used to wrap other $() operations on your page that depend on the DOM being ready to be operated on. While this function is, technically, chainable - there really isn't much use for chaining against it. You can have as many $(document).ready events on your page as you like. See ready(Function) for details about the ready event. 返回值 jQuery 参数 callback (Function) : 当DOM加载完成后要执行的函数 示例 当DOM加载完成后,执行其中的函数。 jQuery 代码: $(function(){ // Document is ready }); -------------------------------------------------------------------------------- Uses both the shortcut for $(document).ready() and the argument to write failsafe jQuery code using the $ alias, without relying on the global alias. jQuery 代码: jQuery(function($) { // Your code using failsafe $ alias here... }); jQuery 对象访问 each(callback)each(callback) 以每一个匹配的元素作为上下文来执行一个函数。 意味着,每次执行传递进来的函数时,函数中的this关键字都指向一个不同的DOM元素(每次都是一个不同的匹配元素)。 而且,在每次执行函数时,都会给函数传递一个表示作为执行环境的元素在匹配的元素集合中所处位置的数字值作为参数(从零开始的整形)。 返回 'false' 将停止循环 (就像在普通的循环中使用 'break')。返回 'true' 跳至下一个循环(就像在普通的循环中使用'continue')。 -------------------------------------------------------------------------------- Execute a function within the context of every matched element. This means that every time the passed-in function is executed (which is once for every element matched) the 'this' keyword points to the specific DOM element. Additionally, the function, when executed, is passed a single argument representing the position of the element in the matched set (integer, zero-index). Returning 'false' from within the each function completely stops the loop through all of the elements (this is like using a 'break' with a normal loop). Returning 'true' from within the loop skips to the next iteration (this is like using a 'continue' with a normal loop). 返回值 jQuery 参数 callback (Function) : 对于每个匹配的元素所要执行的函数 示例 迭代两个图像,并设置它们的 src 属性。注意:此处 this 指代的是 DOM 对象而非 jQuery 对象。 HTML 代码: <img/><img/> jQuery 代码: $("img").each(function(i){ this.src = "test" + i + ".jpg"; }); 结果: [ <img src="test0.jpg" />, <img src="test1.jpg" /> ] -------------------------------------------------------------------------------- 如果你得到 jQuery对象,可以使用 $(this) 函数。 jQuery 代码: $("img").each(function(){ $(this).toggleClass("example"); }); -------------------------------------------------------------------------------- 你可以使用 'return' 来提前跳出 each() 循环。 HTML 代码: <button>Change colors</button> <span></span> <div></div> <div></div> <div></div> <div></div> <div id="stop">Stop here</div> <div></div> <div></div> <div></div> jQuery 代码: $("button").click(function () { $("div").each(function (index, domEle) { // domEle == this $(domEle).css("backgroundColor", "yellow"); if ($(this).is("#stop")) { $("span").text("Stopped at div index #" + index); return false; } }); });size()size() jQuery 对象中元素的个数。 这个函数的返回值与 jQuery 对象的'length' 属性一致。 -------------------------------------------------------------------------------- The number of elements in the jQuery object. This returns the same number as the 'length' property of the jQuery object. 返回值 Number 示例 计算文档中所有图片数量 HTML 代码: <img src="test1.jpg"/> <img src="test2.jpg"/> jQuery 代码: $("img").size(); 结果: 2 lengthlength jQuery 对象中元素的个数。 当前匹配的元素个数。 size 将返回相同的值。 -------------------------------------------------------------------------------- The number of elements in the jQuery object. The number of elements currently matched. The size function will return the same value. 返回值 Number 示例 计算文档中所有图片数量 HTML 代码: <img src="test1.jpg"/> <img src="test2.jpg"/> jQuery 代码: $("img").length; 结果: 2 get()get() 取得所有匹配的 DOM 元素集合。 这是取得所有匹配元素的一种向后兼容的方式(不同于jQuery对象,而实际上是元素数组)。 如果你要直接操作 DOM 对象而不是 jQuery 对象,这个函数非常有用。 -------------------------------------------------------------------------------- Access all matched DOM elements. This serves as a backwards-compatible way of accessing all matched elements (other than the jQuery object itself, which is, in fact, an array of elements). It is useful if you need to operate on the DOM elements themselves instead of using built-in jQuery functions. 返回值 Array<Element> 示例 选择文档中所有图像作为元素数组,并用数组内建的 reverse 方法将数组反向。 HTML 代码: <img src="test1.jpg"/> <img src="test2.jpg"/> jQuery 代码: $("img").get().reverse(); 结果: [ <img src="test2.jpg"/> <img src="test1.jpg"/> ] get(index)get(index) 取得其中一个匹配的元素。 num表示取得第几个匹配的元素。 这能够让你选择一个实际的DOM 元素并且对他直接操作,而不是通过 jQuery 函数。$(this).get(0)与$(this)[0]等价。 -------------------------------------------------------------------------------- Access a single matched DOM element at a specified index in the matched set. This allows you to extract the actual DOM element and operate on it directly without necessarily using jQuery functionality on it. This function called as $(this).get(0) is the equivalent of using square bracket notation on the jQuery object itself like $(this)[0]. 返回值 Element 参数 index (Number) :取得第 index 个位置上的元素 示例 HTML 代码: <img src="test1.jpg"/> <img src="test2.jpg"/> jQuery 代码: $("img").get(0); 结果: [ <img src="test1.jpg"/> ] index(subject)index(subject) 搜索与参数表示的对象匹配的元素,并返回相应元素的索引值值。 如果找到了匹配的元素,从0开始返回;如果没有找到匹配的元素,返回-1。 -------------------------------------------------------------------------------- Searches every matched element for the object and returns the index of the element, if found, starting with zero. Returns -1 if the object wasn't found. 返回值 Number 参数 subject (Element) : 要搜索的对象 示例 返回ID值为foobar的元素的索引值值。 HTML 代码: <div id="foobar"><b></b><span id="foo"></span></div> jQuery 代码: $("*").index($('#foobar')[0]) 结果: 5 插件机制 jQuery.fn.extend(object)jQuery.fn.extend(object) 扩展 jQuery 元素集来提供新的方法(通常用来制作插件)。 查看这里Plugins/Authoring可以获取更多信息。 -------------------------------------------------------------------------------- Extends the jQuery element set to provide new methods (used to make a typical jQuery plugin). Can be used to add functions into the to add plugin methods (plugins). 返回值 jQuery 参数 object (Object) :用来扩充 jQuery 对象。 示例 增加两个插件方法。 jQuery 代码: jQuery.fn.extend({ check: function() { return this.each(function() { this.checked = true; }); }, uncheck: function() { return this.each(function() { this.checked = false; }); } }); 结果: $("input[@type=checkbox]").check(); $("input[@type=radio]").uncheck(); jQuery.extend(object)jQuery.extend(object) 扩展jQuery对象本身。 用来在jQuery命名空间上增加新函数。 查看 'jQuery.fn.extend' 获取更多添加插件的信息。 -------------------------------------------------------------------------------- Extends the jQuery object itself. Can be used to add functions into the jQuery namespace. See 'jQuery.fn.extend' for more information on using this method to add Plugins. 返回值 jQuery 参数 object (Object) : 用以扩展 jQuery 对象 示例 在jQuery命名空间上增加两个函数。 jQuery 代码: jQuery.extend({ min: function(a, b) { return a < b ? a : b; }, max: function(a, b) { return a > b ? a : b; } }); 结果: jQuery.min(2,3); // => 2 jQuery.max(4,5); // => 5 多库共存 jQuery.noConflict()jQuery.noConflict() 运行这个函数将变量$的控制权让渡给第一个实现它的那个库。 这有助于确保jQuery不会与其他库的$对象发生冲突。在运行这个函数后,就只能使用jQuery变量访问jQuery对象。例如,在要用到$("div p")的地方,就必须换成jQuery("div p")。 -------------------------------------------------------------------------------- Run this function to give control of the $ variable back to whichever library first implemented it. This helps to make sure that jQuery doesn't conflict with the $ object of other libraries. By using this function, you will only be able to access jQuery using the 'jQuery' variable. For example, where you used to do $("div p"), you now must do jQuery("div p"). 返回值 jQuery 示例 将$引用的对象映射回原始的对象。 jQuery 代码: jQuery.noConflict(); // 使用 jQuery jQuery("div p").hide(); // 使用其他库的 $() $("content").style.display = 'none'; -------------------------------------------------------------------------------- 恢复使用别名$,然后创建并执行一个函数,在这个函数的作用域中仍然将$作为jQuery的别名来使用。在这个函数中,原来的$对象是无效的。这个函数对于大多数不依赖于其他库的插件都十分有效。 jQuery 代码: jQuery.noConflict(); (function($) { $(function() { // 使用 $ 作为 jQuery 别名的代码 }); })(jQuery); // 其他用 $ 作为别名的库的代码 -------------------------------------------------------------------------------- 创建一个新的别名用以在接下来的库中使用jQuery对象。 jQuery 代码: var j = jQuery.noConflict(); // 基于 jQuery 的代码 j("div p").hide(); // 基于其他库的 $() 代码 $("content").style.display = 'none'; jQuery.noConflict(extreme)jQuery.noConflict(extreme) 将$和jQuery的控制权都交还给原来的库。用之前请考虑清楚! 这是相对于简单的 noConflict 方法更极端的版本,因为这将完全重新定义jQuery。这通常用于一种极端的情况,比如你要将jQuery嵌入一个高度冲突的环境。注意:调用此方法后极有可能导致插件失效。 -------------------------------------------------------------------------------- Revert control of both the $ and jQuery variables to their original owners. Use with discretion. This is a more-extreme version of the simple noConflict method, as this one will completely undo what jQuery has introduced. This is to be used in an extreme case where you'd like to embed jQuery into a high-conflict environment. NOTE: It's very likely that plugins won't work after this particular method has been called. 返回值 jQuery 参数 extreme (Boolean) : 传入 true 来允许彻底将jQuery变量还原 示例 完全将 jQuery 移到一个新的命名空间。 jQuery 代码: var dom = {}; dom.query = jQuery.noConflict(true); 结果: // 新 jQuery 的代码 dom.query("div p").hide(); // 另一个库 $() 的代码 $("content").style.display = 'none'; // 另一个版本 jQuery 的代码 jQuery("div > p").hide(); 选择器基本 #id#id 根据给定的ID匹配一个元素。 -------------------------------------------------------------------------------- Matches a single element with the given id attribute. 返回值 Element 参数 id (String) : 用于搜索的,通过元素的 id 属性中给定的值 示例 查找 ID 为"myDiv"的元素。 HTML 代码: <div id="notMe"><p>id="notMe"</p></div> <div id="myDiv">id="myDiv"</div> jQuery 代码: $("#myDiv"); 结果: [ <div id="myDiv">id="myDiv"</div> ] elementelement 根据给定的元素名匹配所有元素 -------------------------------------------------------------------------------- Matches all elements with the given name. 返回值 Array<Element> 参数 element (String) : 一个用于搜索的元素。指向 DOM 节点的标签名。 示例 查找一个 DIV 元素。 HTML 代码: <div>DIV1</div> <div>DIV2</div> <span>SPAN</span> jQuery 代码: $("div"); 结果: [ <div>DIV1</div>, <div>DIV2</div> ] .class.class 根据给定的类匹配元素。 -------------------------------------------------------------------------------- Matches all elements with the given class. 返回值 Array<Element> 参数 class (String) : 一个用以搜索的类。一个元素可以有多个类,只要有一个符合就能被匹配到。 示例 查找所有类是 "myClass" 的元素. HTML 代码: <div class="notMe">div class="notMe"</div> <div class="myClass">div class="myClass"</div> <span class="myClass">span class="myClass"</span> jQuery 代码: $(".myClass"); 结果: [ <div class="myClass">div class="myClass"</div>, <span class="myClass">span class="myClass"</span> ] ** 匹配所有元素 多用于结合上下文来搜索。 -------------------------------------------------------------------------------- Matches all elements. Most useful when combined with a context to search in. 返回值 Array<Element> 示例 找到每一个元素 HTML 代码: <div>DIV</div> <span>SPAN</span> <p>P</p> jQuery 代码: $("*") 结果: [ <div>DIV</div>, <span>SPAN</span>, <p>P</p> ] selector1,selector2,selectorNselector1,selector2,selectorN 将每一个选择器匹配到的元素合并后一起返回。 你可以指定任意多个选择器,并将匹配到的元素合并到一个结果内。 -------------------------------------------------------------------------------- Matches the combined results of all the specified selectors. You can specify any number of selectors to combine into a single result. 返回值 Array<Element> 参数 selector1 (Selector) : 一个有效的选择器 selector2 (Selector) : 另一个有效的选择器 selectorN (Selector) : (可选) 任意多个有效选择器 示例 找到匹配任意一个类的元素。 HTML 代码: <div>div</div> <p class="myClass">p class="myClass"</p> <span>span</span> <p class="notMyClass">p class="notMyClass"</p> jQuery 代码: $("div,span,p.myClass") 结果: [ <div>div</div>, <p class="myClass">p class="myClass"</p>, <span>span</span> ] 层级 ancestor descendantancestor descendant 在给定的祖先元素下匹配所有的后代元素 -------------------------------------------------------------------------------- Matches all descendant elements specified by descendant of elements specified by ancestor. 返回值 Array<Element> 参数 ancestor (Selector) : 任何有效选择器 descendant (Selector) : 用以匹配元素的选择器,并且它是第一个选择器的后代元素 示例 找到表单中所有的 input 元素 HTML 代码: <form> <label>Name:</label> <input name="name" /> <fieldset> <label>Newsletter:</label> <input name="newsletter" /> </fieldset> </form> <input name="none" /> jQuery 代码: $("form input") 结果: [ <input name="name" />, <input name="newsletter" /> ] parent > childparent > child 在给定的父元素下匹配所有的子元素 -------------------------------------------------------------------------------- Matches all child elements specified by child of elements specified by parent. 返回值 Array<Element> 参数 parent (Selector) : 任何有效选择器 child (Selector) : 用以匹配元素的选择器,并且它是第一个选择器的子元素 示例 匹配表单中所有的子级input元素。 HTML 代码: <form> <label>Name:</label> <input name="name" /> <fieldset> <label>Newsletter:</label> <input name="newsletter" /> </fieldset> </form> <input name="none" /> jQuery 代码: $("form > input") 结果: [ <input name="name" /> ] prev + nextprev + next 匹配所有紧接在 prev 元素后的 next 元素 -------------------------------------------------------------------------------- Matches all next elements specified by next that are next to elements specified by prev. 返回值 Array<Element> 参数 prev (Selector) : 任何有效选择器 next (Selector) :一个有效选择器并且紧接着第一个选择器 示例 匹配所有跟在 label 后面的 input 元素 HTML 代码: <form> <label>Name:</label> <input name="name" /> <fieldset> <label>Newsletter:</label> <input name="newsletter" /> </fieldset> </form> <input name="none" /> jQuery 代码: $("label + input") 结果: [ <input name="name" />, <input name="newsletter" /> ] prev ~ siblingsprev ~ siblings 匹配 prev 元素之后的所有 siblings 元素 -------------------------------------------------------------------------------- Matches all sibling elements after the "prev" element that match the filtering "siblings" selector. 返回值 Array<Element> 参数 prev (Selector) : 任何有效选择器 siblings (Selector) : 一个选择器,并且它作为第一个选择器的同辈 示例 找到所有与表单同辈的 input 元素 HTML 代码: <form> <label>Name:</label> <input name="name" /> <fieldset> <label>Newsletter:</label> <input name="newsletter" /> </fieldset> </form> <input name="none" /> jQuery 代码: $("form ~ input") 结果: [ <input name="none" /> ] 简单 :first:first 匹配找到的第一个元素 -------------------------------------------------------------------------------- Matches the first selected element. 返回值 Element 示例 查找表格的第一行 HTML 代码: <table> <tr><td>Header 1</td></tr> <tr><td>Value 1</td></tr> <tr><td>Value 2</td></tr> </table> jQuery 代码: $("tr:first") 结果: [ <tr><td>Header 1</td></tr> ] :last:last 匹配找到的最后一个元素 -------------------------------------------------------------------------------- Matches the last selected element. 返回值 Element 示例 查找表格的最后一行 HTML 代码: <table> <tr><td>Header 1</td></tr> <tr><td>Value 1</td></tr> <tr><td>Value 2</td></tr> </table> jQuery 代码: $("tr:last") 结果: [ <tr><td>Value 2</td></tr> ] :not(selector):not(selector) 去除所有与给定选择器匹配的元素 -------------------------------------------------------------------------------- Removes all elements matching the given selector. 返回值 Array<Element> 参数 selector (Selector) : 用于筛选的选择器 示例 查找所有未选中的 input 元素 HTML 代码: <input name="apple" /> <input name="flower" checked="checked" /> jQuery 代码: $("input:not(:checked)") 结果: [ <input name="apple" /> ] :even:even 匹配所有索引值为偶数的元素,从 0 开始计数 -------------------------------------------------------------------------------- Matches even elements, zero-indexed. 返回值 Array<Element> 示例 查找表格的1、3、5...行(即索引值0、2、4...) HTML 代码: <table> <tr><td>Header 1</td></tr> <tr><td>Value 1</td></tr> <tr><td>Value 2</td></tr> </table> jQuery 代码: $("tr:even") 结果: [ <tr><td>Header 1</td></tr>, <tr><td>Value 2</td></tr> ] :odd:odd 匹配所有索引值为奇数的元素,从 0 开始计数 -------------------------------------------------------------------------------- Matches odd elements, zero-indexed. 返回值 Array<Element> 示例 查找表格的2、4、6行(即索引值1、3、5...) HTML 代码: <table> <tr><td>Header 1</td></tr> <tr><td>Value 1</td></tr> <tr><td>Value 2</td></tr> </table> jQuery 代码: $("tr:odd") 结果: [ <tr><td>Value 1</td></tr> ] :eq(index):eq(index) 匹配一个给定索引值的元素 -------------------------------------------------------------------------------- Matches a single element by its index. 返回值 Element 参数 index (Number) : 从 0 开始计数 示例 查找第二行 HTML 代码: <table> <tr><td>Header 1</td></tr> <tr><td>Value 1</td></tr> <tr><td>Value 2</td></tr> </table> jQuery 代码: $("tr:eq(1)") 结果: [ <tr><td>Value 1</td></tr> ] :gt(index):gt(index) 匹配所有大于给定索引值的元素 -------------------------------------------------------------------------------- Matches all elements with an index above the given one. 返回值 Array<Element> 参数 index (Number) : 从 0 开始计数 示例 查找第二第三行,即索引值是1和2,也就是比0大 HTML 代码: <table> <tr><td>Header 1</td></tr> <tr><td>Value 1</td></tr> <tr><td>Value 2</td></tr> </table> jQuery 代码: $("tr:gt(0)") 结果: [ <tr><td>Value 1</td></tr>, <tr><td>Value 2</td></tr> ] :lt(index):lt(index) 匹配所有小于给定索引值的元素 -------------------------------------------------------------------------------- Matches all elements with an index below the given one. 返回值 Array<Element> 参数 index (Number) : 从 0 开始计数 示例 查找第一第二行,即索引值是0和1,也就是比2小 HTML 代码: <table> <tr><td>Header 1</td></tr> <tr><td>Value 1</td></tr> <tr><td>Value 2</td></tr> </table> jQuery 代码: $("tr:lt(2)") 结果: [ <tr><td>Header 1</td></tr>, <tr><td>Value 1</td></tr> ] :header:header 匹配如 h1, h2, h3之类的标题元素 -------------------------------------------------------------------------------- Matches all elements that are headers, like h1, h2, h3 and so on. 返回值 Array<Element> 示例 给页面内所有标题加上背景色 HTML 代码: <h1>Header 1</h1> <p>Contents 1</p> <h2>Header 2</h2> <p>Contents 2</p> jQuery 代码: $(":header").css("background", "#EEE"); 结果: [ <h1 style="background:#EEE;">Header 1</h1>, <h2 style="background:#EEE;">Header 2</h2> ] :animated:animated 匹配所有没有在执行动画效果中的元素 -------------------------------------------------------------------------------- Matches all elements that are currently being animated. 返回值 Array<Element> 示例 只有对不在执行动画效果的元素执行一个动画特效 HTML 代码: <button id="run">Run</button><div></div> jQuery 代码: $("#run").click(function(){ $("div:not(:animated)").animate({ left: "+20" }, 1000); }); 内容 :contains(text):contains(text) 匹配包含给定文本的元素 -------------------------------------------------------------------------------- Matches elements which contain the given text. 返回值 Array<Element> 参数 text (String) : 一个用以查找的字符串 示例 查找所有包含 "John" 的 div 元素 HTML 代码: <div>John Resig</div> <div>George Martin</div> <div>Malcom John Sinclair</div> <div>J. Ohn jQuery 代码: $("div:contains('John')") 结果: [ <div>John Resig</div>, <div>Malcom John Sinclair</div> ] :empty:empty 匹配所有不包含子元素或者文本的空元素 -------------------------------------------------------------------------------- Matches all elements that are empty, be it elements or text. 返回值 Array<Element> 示例 查找所有不包含子元素或者文本的空元素 HTML 代码: <table> <tr><td>Value 1</td><td></td></tr> <tr><td>Value 2</td><td></td></tr> </table> jQuery 代码: $("td:empty") 结果: [ <td></td>, <td></td> ] :has(selector):has(selector) 匹配含有选择器所匹配的元素的元素 -------------------------------------------------------------------------------- Matches elements which contain at least one element that matches the specified selector. 返回值 Array<Element> 参数 selector (Selector) : 一个用于筛选的选择器 示例 给所有包含 p 元素的 div 元素添加一个 text 类 HTML 代码: <div><p>Hello</p></div> <div>Hello again!</div> jQuery 代码: $("div:has(p)").addClass("test"); 结果: [ <div class="test"><p>Hello</p></div> ] :parent:parent 匹配含有子元素或者文本的元素 -------------------------------------------------------------------------------- Matches all elements that are parents - they have child elements, including text. 返回值 Array<Element> 示例 查找所有含有子元素或者文本的 td 元素 HTML 代码: <table> <tr><td>Value 1</td><td></td></tr> <tr><td>Value 2</td><td></td></tr> </table> jQuery 代码: $("td:parent") 结果: [ <td>Value 1</td>, <td>Value 1</td> ] 可见性 :hidden:hidden 匹配所有的不可见元素,input 元素的 type 属性为 "hidden" 的话也会被匹配到 -------------------------------------------------------------------------------- Matches all elements that are hidden, or input elements of type "hidden". 返回值 Array<Element> 示例 查找所有不可见的 tr 元素 HTML 代码: <table> <tr style="display:none"><td>Value 1</td></tr> <tr><td>Value 2</td></tr> </table> jQuery 代码: $("tr:hidden") 结果: [ <tr style="display:none"><td>Value 1</td></tr> ] :visible:visible 匹配所有的可见元素 -------------------------------------------------------------------------------- Matches all elements that are visible. 返回值 Array<Element> 示例 查找所有可见的 tr 元素 HTML 代码: <table> <tr style="display:none"><td>Value 1</td></tr> <tr><td>Value 2</td></tr> </table> jQuery 代码: $("tr:visible") 结果: [ <tr><td>Value 2</td></tr> ] 属性 [attribute][attribute] 匹配包含给定属性的元素 -------------------------------------------------------------------------------- Matches elements that have the specified attribute. 返回值 Array<Element> 参数 attribute (String) : 属性名 示例 查找所有含有 id 属性的 div 元素 HTML 代码: <div> <p>Hello!</p> </div> <div id="test2"></div> jQuery 代码: $("div[id]") 结果: [ <div id="test2"></div> ] [attribute=value][attribute=value] 匹配给定的属性是某个特定值的元素 -------------------------------------------------------------------------------- Matches elements that have the specified attribute with a certain value. 返回值 Array<Element> 参数 attribute (String) : 属性名 value (String) : 属性值。引号在大多数情况下是可选的。但在遇到诸如属性值包含"]"时,用以避免冲突。 示例 查找所有 name 属性是 newsletter 的 input 元素 HTML 代码: '<input type="checkbox" name="newsletter" value="Hot Fuzz" /> <input type="checkbox" name="newsletter" value="Cold Fusion" /> <input type="checkbox" name="accept" value="Evil Plans" /> jQuery 代码: $("input[name='newsletter']").attr("checked", true); 结果: [ <input type="checkbox" name="newsletter" value="Hot Fuzz" checked="true" />, <input type="checkbox" name="newsletter" value="Cold Fusion" checked="true" /> ] [attribute!=value][attribute!=value] 匹配给定的属性是不包含某个特定值的元素 -------------------------------------------------------------------------------- Matches elements that don't have the specified attribute with a certain value. 返回值 Array<Element> 参数 attribute (String) : 属性名 value (String) : 属性值。引号在大多数情况下是可选的。但在遇到诸如属性值包含"]"时,用以避免冲突。 示例 查找所有 name 属性不是 newsletter 的 input 元素 HTML 代码: '<input type="checkbox" name="newsletter" value="Hot Fuzz" /> <input type="checkbox" name="newsletter" value="Cold Fusion" /> <input type="checkbox" name="accept" value="Evil Plans" /> jQuery 代码: $("input[name!='newsletter']").attr("checked", true); 结果: [ <input type="checkbox" name="accept" value="Evil Plans" checked="true" /> ] [attribute^=value][attribute^=value] 匹配给定的属性是以某些值开始的元素 -------------------------------------------------------------------------------- Matches elements that have the specified attribute and it starts with a certain value. 返回值 Array<Element> 参数 attribute (String) : 属性名 value ( String) : 属性值。引号在大多数情况下是可选的。但在遇到诸如属性值包含"]"时,用以避免冲突。 示例 查找所有 name 以 'news' 开始的 input 元素 HTML 代码: <input name="newsletter" /> <input name="milkman" /> <input name="newsboy" /> jQuery 代码: $("input[name^='news']") 结果: [ <input name="newsletter" />, <input name="newsboy" /> ] [attribute$=value][attribute$=value] 匹配给定的属性是以某些值结尾的元素 -------------------------------------------------------------------------------- Matches elements that have the specified attribute and it ends with a certain value. 返回值 Array<Element> 参数 attribute (String) : 属性名 value (String) : 属性值。引号在大多数情况下是可选的。但在遇到诸如属性值包含"]"时,用以避免冲突。 示例 查找所有 name 以 'letter' 结尾的 input 元素 HTML 代码: <input name="newsletter" /> <input name="milkman" /> <input name="jobletter" /> jQuery 代码: $("input[name$='letter']") 结果: [ <input name="newsletter" />, <input name="jobletter" /> ] [attribute*=value][attribute*=value] 匹配给定的属性是以包含某些值的元素 -------------------------------------------------------------------------------- Matches elements that have the specified attribute and it contains a certain value. 返回值 Array<Element> 参数 attribute (String) : 属性名 value (String) : 属性值。引号在大多数情况下是可选的。但在遇到诸如属性值包含"]"时,用以避免冲突。 示例 查找所有 name 包含 'man' 的 input 元素 HTML 代码: <input name="man-news" /> <input name="milkman" /> <input name="letterman2" /> <input name="newmilk" /> jQuery 代码: $("input[name*='man']") 结果: [ <input name="man-news" />, <input name="milkman" />, <input name="letterman2" /> ] [selector1][selector2][selectorN][selector1][selector2][selectorN] 复合属性选择器,需要同时满足多个条件时使用。 -------------------------------------------------------------------------------- Matches elements that have the specified attribute and it contains a certain value. 返回值 Array<Element> 参数 selector1 (Selector) : 属性选择器 selector2 (Selector) : 另一个属性选择器,用以进一步缩小范围 selectorN (Selector) : 任意多个属性选择器 示例 找到所有含有 id 属性,并且它的 name 属性是以 man 结尾的 HTML 代码: <input id="man-news" name="man-news" /> <input name="milkman" /> <input id="letterman" name="new-letterman" /> <input name="newmilk" /> jQuery 代码: $("input[id][name$='man']") 结果: [ <input id="letterman" name="new-letterman" /> ] 子元素 :nth-child(index/even/odd/equation):nth-child(index/even/odd/equation) 匹配其父元素下的第N个子或奇偶元素 ':eq(index)' 只匹配一个元素,而这个将为每一个父元素匹配子元素。:nth-child从1开始的,而:eq()是从0算起的! 可以使用: nth-child(even) :nth-child(odd) :nth-child(3n) :nth-child(2) :nth-child(3n+1) :nth-child(3n+2) -------------------------------------------------------------------------------- Matches the nth-child of its parent. While ':eq(index)' matches only a single element, this matches more then one: One for each parent. The specified index is one-indexed, in contrast to :eq() which starst at zero. 返回值 Array<Element> 参数 index (Number) : 要匹配元素的序号,从1开始 示例 在每个 ul 查找第 2 个li HTML 代码: <ul> <li>John</li> <li>Karl</li> <li>Brandon</li> </ul> <ul> <li>Glen</li> <li>Tane</li> <li>Ralph</li> </ul> jQuery 代码: $("ul li:nth-child(2)") 结果: [ <li>Karl</li>, <li>Tane</li> ] :first-child:first-child 匹配第一个子元素 ':first' 只匹配一个元素,而此选择符将为每个父元素匹配一个子元素 -------------------------------------------------------------------------------- Matches the first child of its parent. While ':first' matches only a single element, this matches more then one: One for each parent. 返回值 Array<Element> 示例 在每个 ul 中查找第一个 li HTML 代码: <ul> <li>John</li> <li>Karl</li> <li>Brandon</li> </ul> <ul> <li>Glen</li> <li>Tane</li> <li>Ralph</li> </ul> jQuery 代码: $("ul li:first-child") 结果: [ <li>John</li>, <li>Glen</li> ] :last-child:last-child 匹配最后一个子元素 ':last'只匹配一个元素,而此选择符将为每个父元素匹配一个子元素 -------------------------------------------------------------------------------- Matches the last child of its parent. While ':last' matches only a single element, this matches more then one: One for each parent. 返回值 Array<Element> 示例 在每个 ul 中查找最后一个 li HTML 代码: <ul> <li>John</li> <li>Karl</li> <li>Brandon</li> </ul> <ul> <li>Glen</li> <li>Tane</li> <li>Ralph</li> </ul> jQuery 代码: $("ul li:last-child") 结果: [ <li>Brandon</li>, <li>Ralph</li> ] :only-child:only-child 如果某个元素是父元素中唯一的子元素,那将会被匹配 如果父元素中含有其他元素,那将不会被匹配。 -------------------------------------------------------------------------------- Matches the only child of its parent. If the parent has other child elements, nothing is matched. 返回值 Array<Element> 示例 在 ul 中查找是唯一子元素的 li HTML 代码: <ul> <li>John</li> <li>Karl</li> <li>Brandon</li> </ul> <ul> <li>Glen</li> jQuery 代码: $("ul li:only-child") 结果: [ <li>Glen</li> ] 表单 :input:input 匹配所有 input, textarea, select 和 button 元素 -------------------------------------------------------------------------------- Matches all input, textarea, select and button elements. 返回值 Array<Element> 示例 查找所有的input元素 HTML 代码: <form> <input type="text" /> <input type="checkbox" /> <input type="radio" /> <input type="image" /> <input type="file" /> <input type="submit" /> <input type="reset" /> <input type="password" /> <input type="button" /> <select><option/></select> <textarea></textarea> <button></button> </form> jQuery 代码: $(":input") 结果: [ <input type="text" />, <input type="checkbox" />, <input type="radio" />, <input type="image" />, <input type="file" />, <input type="submit" />, <input type="reset" />, <input type="password" />, <input type="button" /> ] :text:text 匹配所有的单行文本框 -------------------------------------------------------------------------------- Matches all input elements of type text. 返回值 Array<Element> 示例 查找所有文本框 HTML 代码: <form> <input type="text" /> <input type="checkbox" /> <input type="radio" /> <input type="image" /> <input type="file" /> <input type="submit" /> <input type="reset" /> <input type="password" /> <input type="button" /> <select><option/></select> <textarea></textarea> <button></button> </form> jQuery 代码: $(":text") 结果: [ <input type="text" /> ] :password:password 匹配所有密码框 -------------------------------------------------------------------------------- Matches all input elements of type password. 返回值 Array<Element> 示例 查找所有密码框 HTML 代码: <form> <input type="text" /> <input type="checkbox" /> <input type="radio" /> <input type="image" /> <input type="file" /> <input type="submit" /> <input type="reset" /> <input type="password" /> <input type="button" /> <select><option/></select> <textarea></textarea> <button></button> </form> jQuery 代码: $(":password") 结果: [ <input type="password" /> ] :radio:radio 匹配所有单选按钮 -------------------------------------------------------------------------------- Matches all input elements of type radio. 返回值 Array<Element> 示例 查找所有单选按钮 HTML 代码: <form> <input type="text" /> <input type="checkbox" /> <input type="radio" /> <input type="image" /> <input type="file" /> <input type="submit" /> <input type="reset" /> <input type="password" /> <input type="button" /> <select><option/></select> <textarea></textarea> <button></button> </form> jQuery 代码: $(":radio") 结果: [ <input type="radio" /> ] :checkbox:checkbox 匹配所有复选框 -------------------------------------------------------------------------------- Matches all input elements of type checkbox. 返回值 Array<Element> 示例 查找所有复选框 HTML 代码: <form> <input type="text" /> <input type="checkbox" /> <input type="radio" /> <input type="image" /> <input type="file" /> <input type="submit" /> <input type="reset" /> <input type="password" /> <input type="button" /> <select><option/></select> <textarea></textarea> <button></button> </form> jQuery 代码: $(":checkbox") 结果: [ <input type="checkbox" /> ] :submit:submit 匹配所有提交按钮 -------------------------------------------------------------------------------- Matches all input elements of type submit. 返回值 Array<Element> 示例 查找所有提交按钮 HTML 代码: <form> <input type="text" /> <input type="checkbox" /> <input type="radio" /> <input type="image" /> <input type="file" /> <input type="submit" /> <input type="reset" /> <input type="password" /> <input type="button" /> <select><option/></select> <textarea></textarea> <button></button> </form> jQuery 代码: $(":submit") 结果: [ <input type="submit" /> ] :image:image 匹配所有图像域 -------------------------------------------------------------------------------- Matches all input elements of type image. 返回值 Array<Element> 示例 匹配所有图像域 HTML 代码: <form> <input type="text" /> <input type="checkbox" /> <input type="radio" /> <input type="image" /> <input type="file" /> <input type="submit" /> <input type="reset" /> <input type="password" /> <input type="button" /> <select><option/></select> <textarea></textarea> <button></button> </form> jQuery 代码: $(":image") 结果: [ <input type="image" /> ] :reset:reset 匹配所有重置按钮 -------------------------------------------------------------------------------- Matches all input elements of type reset. 返回值 Array<Element> 示例 查找所有重置按钮 HTML 代码: <form> <input type="text" /> <input type="checkbox" /> <input type="radio" /> <input type="image" /> <input type="file" /> <input type="submit" /> <input type="reset" /> <input type="password" /> <input type="button" /> <select><option/></select> <textarea></textarea> <button></button> </form> jQuery 代码: $(":reset") 结果: [ <input type="reset" /> ] :button:button 匹配所有按钮 -------------------------------------------------------------------------------- Matches all input elements of type button. 返回值 Array<Element> 示例 查找所有按钮. HTML 代码: <form> <input type="text" /> <input type="checkbox" /> <input type="radio" /> <input type="image" /> <input type="file" /> <input type="submit" /> <input type="reset" /> <input type="password" /> <input type="button" /> <select><option/></select> <textarea></textarea> <button></button> </form> jQuery 代码: $(":button") 结果: [ <input type="button" />,<button></button> ] :file:file 匹配所有文件域 -------------------------------------------------------------------------------- Matches all input elements of type file. 返回值 Array<Element> 示例 查找所有文件域 HTML 代码: <form> <input type="text" /> <input type="checkbox" /> <input type="radio" /> <input type="image" /> <input type="file" /> <input type="submit" /> <input type="reset" /> <input type="password" /> <input type="button" /> <select><option/></select> <textarea></textarea> <button></button> </form> jQuery 代码: $(":file") 结果: [ <input type="file" /> ] :hidden:hidden 匹配所有不可见元素,或者type为hidden的元素 -------------------------------------------------------------------------------- Matches all elements that are hidden, or input elements of type "hidden". 返回值 Array<Element> 示例 查找隐藏的 tr HTML 代码: <table> <tr style="display:none"><td>Value 1</td></tr> <tr><td>Value 2</td></tr> </table> jQuery 代码: $("tr:hidden") 结果: [ <tr style="display:none"><td>Value 1</td></tr> ] -------------------------------------------------------------------------------- 匹配type为hidden的元素 HTML 代码: <form> <input type="text" name="email" /> <input type="hidden" name="id" /> </form> jQuery 代码: $("input:hidden") 结果: [ <input type="hidden" name="id" /> ] 表单对象属性 :enabled:enabled 匹配所有可用元素 -------------------------------------------------------------------------------- Matches all elements that are enabled. 返回值 Array<Element> 示例 查找所有可用的input元素 HTML 代码: <form> <input name="email" disabled="disabled" /> <input name="id" /> </form> jQuery 代码: $("input:enabled") 结果: [ <input name="id" /> ] :disabled:disabled 匹配所有不可用元素 -------------------------------------------------------------------------------- Matches all elements that are disabled. 返回值 Array<Element> 示例 查找所有不可用的input元素 HTML 代码: <form> <input name="email" disabled="disabled" /> <input name="id" /> </form> jQuery 代码: $("input:disabled") 结果: [ <input name="email" disabled="disabled" /> ] :checked:checked 匹配所有选中的复选框元素 -------------------------------------------------------------------------------- Matches all elements that are checked. 返回值 Array<Element> 示例 查找所有选中的复选框元素 HTML 代码: <form> <input type="checkbox" name="newsletter" checked="checked" value="Daily" /> <input type="checkbox" name="newsletter" value="Weekly" /> <input type="checkbox" name="newsletter" checked="checked" value="Monthly" /> </form> jQuery 代码: $("input:checked") 结果: [ <input type="checkbox" name="newsletter" checked="checked" value="Daily" />, <input type="checkbox" name="newsletter" checked="checked" value="Monthly" /> ] :selected:selected 匹配所有选中的选项元素 -------------------------------------------------------------------------------- Matches all elements that are selected. 返回值 Array<Element> 示例 查找所有选中的选项元素 HTML 代码: <select> <option value="1">Flowers</option> <option value="2" selected="selected">Gardens</option> <option value="3">Trees</option> </select> jQuery 代码: $("select option:selected") 结果: [ <option value="2" selected="selected">Gardens</option> ] -------------------------------------------------------------------------------- Finds all option elements that are selected. HTML 代码: <select multiple="multiple"> <option value="1">Flowers</option> <option value="2" selected="selected">Gardens</option> <option value="3" selected="selected">Trees</option> </select> jQuery 代码: $("select option:selected") 结果: [ <option value="2" selected="selected">Gardens</option>, <option value="3" selected="selected">Trees</option> ] 属性属性 attr(name)attr(name) 取得第一个匹配元素的属性值。通过这个方法可以方便地从第一个匹配元素中获取一个属性的值。如果元素没有相应属性,则返回 undefined 。 -------------------------------------------------------------------------------- Access a property on the first matched element. This method makes it easy to retrieve a property value from the first matched element. If the element does not have an attribute with such a name, undefined is returned. 返回值 Object 参数 name (String) : 属性名称 示例 返回文档中第一个图像的src属性值。 HTML 代码: <img src="test.jpg"/> jQuery 代码: $("img").attr("src"); 结果: test.jpg attr(properties)attr(properties) 将一个“名/值”形式的对象设置为所有匹配元素的属性。 这是一种在所有匹配元素中批量设置很多属性的最佳方式。 注意,如果你要设置对象的class属性,你必须使用'className' 作为属性名。或者你可以直接使用.addClass( class ) 和 .removeClass( class ). -------------------------------------------------------------------------------- Set a key/value object as properties to all matched elements. This serves as the best way to set a large number of properties on all matched elements. Note that you must use 'className' as key if you want to set the class-Attribute. Or use .addClass( class ) or .removeClass( class ). 返回值 jQuery 参数 properties (Map) : 作为属性的“名/值对”对象 示例 为所有图像设置src和alt属性。 HTML 代码: <img/> jQuery 代码: $("img").attr({ src: "test.jpg", alt: "Test Image" }); 结果: [ <img src= "test.jpg" alt:="Test Image" /> ] -------------------------------------------------------------------------------- attr(key,value)attr(key,value) 为所有匹配的元素设置一个属性值。 -------------------------------------------------------------------------------- Set a single property to a value, on all matched elements. 返回值 jQuery 参数 key (String) : 属性名称 value (Object) : 属性值 示例 为所有图像设置src属性。 HTML 代码: <img/> <img/> jQuery 代码: $("img").attr("src","test.jpg"); 结果: [ <img src= "test.jpg" /> , <img src= "test.jpg" /> ] attr(key,fn)attr(key,fn) 为所有匹配的元素设置一个计算的属性值。 不提供值,而是提供一个函数,由这个函数计算的值作为属性值。 -------------------------------------------------------------------------------- Set a single property to a computed value, on all matched elements. Instead of supplying a string value as described 'above', a function is provided that computes the value. 返回值 jQuery 参数 key (String) : 属性名称 fn (Function) : 返回值的函数 范围:当前元素, 参数: 当前元素的索引值 示例 把src属性的值设置为title属性的值。 HTML 代码: <img src="test.jpg"/> jQuery 代码: $("img").attr("title", function() { return this.src }); 结果: <img src="test.jpg" title="test.jpg" /> removeAttr(name)removeAttr(name) 从每一个匹配的元素中删除一个属性 -------------------------------------------------------------------------------- Remove an attribute from each of the matched elements. 返回值 jQuery 参数 name (String) : 要删除的属性名 示例 将文档中图像的src属性删除 HTML 代码: <img src="test.jpg"/> jQuery 代码: $("img").removeAttr("src"); 结果: [ <img /> ] 类 addClass(class)addClass(class) 为每个匹配的元素添加指定的类名。 -------------------------------------------------------------------------------- Adds the specified class(es) to each of the set of matched elements. 返回值 jQuery 参数 class (String) : 一个或多个要添加到元素中的CSS类名,请用空格分开 示例 为匹配的元素加上 'selected' 类 HTML 代码: <p>Hello</p> jQuery 代码: $("p").addClass("selected"); 结果: [ <p class="selected">Hello</p> ] -------------------------------------------------------------------------------- 为匹配的元素加上 selected highlight 类 HTML 代码: <p>Hello</p> jQuery 代码: $("p").addClass("selected highlight"); 结果: [ <p class="selected highlight">Hello</p> ] removeClass(class)removeClass(class) 从所有匹配的元素中删除全部或者指定的类。 -------------------------------------------------------------------------------- Removes all or the specified class(es) from the set of matched elements. 返回值 jQuery 参数 class (String) : (可选) 一个或多个要删除的CSS类名,请用空格分开 示例 从匹配的元素中删除 'selected' 类 HTML 代码: <p class="selected first">Hello</p> jQuery 代码: $("p").removeClass("selected"); 结果: [ <p>Hello</p> ] -------------------------------------------------------------------------------- 删除匹配元素的所有类 HTML 代码: <p class="selected first">Hello</p> jQuery 代码: $("p").removeClass(); 结果: [ <p>Hello</p> ] toggleClass(class)toggleClass(class) 如果存在(不存在)就删除(添加)一个类。 -------------------------------------------------------------------------------- Adds the specified class if it is not present, removes the specified class if it is present. 返回值 jQuery 参数 class (String) :CSS类名 示例 为匹配的元素切换 'selected' 类 HTML 代码: <p>Hello</p><p class="selected">Hello Again</p> jQuery 代码: $("p").toggleClass("selected"); 结果: [ <p class="selected">Hello</p>, <p>Hello Again</p> ] Html代码 html()html() 取得第一个匹配元素的html内容。这个函数不能用于XML文档。但可以用于XHTML文档。 -------------------------------------------------------------------------------- Get the html contents of the first matched element. This property is not available on XML documents (although it will work for XHTML documents). 返回值 String 示例 HTML 代码: <div><p>Hello</p></div> jQuery 代码: $("div").html(); 结果: Hello html(val)html(val) 设置每一个匹配元素的html内容。这个函数不能用于XML文档。但可以用于XHTML文档。 -------------------------------------------------------------------------------- Set the html contents of every matched element. This property is not available on XML documents (although it will work for XHTML documents). 返回值 jQuery 参数 val (String) : 用于设定HTML内容的值 示例 HTML 代码: <div></div> jQuery 代码: $("div").html("<p>Hello Again</p>"); 结果: [ <div><p>Hello Again</p></div> ] 文本 text()text() 取得所有匹配元素的内容。 结果是由所有匹配元素包含的文本内容组合起来的文本。这个方法对HTML和XML文档都有效。 -------------------------------------------------------------------------------- Get the text contents of all matched elements. The result is a string that contains the combined text contents of all matched elements. This method works on both HTML and XML documents. 返回值 String 示例 HTML 代码: <p><b>Test</b> Paragraph.</p><p>Paraparagraph</p> jQuery 代码: $("p").text(); 结果: Test Paragraph.Paraparagraph text(val)text(val) 设置所有匹配元素的文本内容 与 html() 类似, 但将编码 HTML (将 "<" 和 ">" 替换成相应的HTML实体). -------------------------------------------------------------------------------- Set the text contents of all matched elements. Similar to html(), but escapes HTML (replace "<" and ">" with their HTML entities). 返回值 jQuery 参数 val (String) : 用于设置元素内容的文本 示例 HTML 代码: <p>Test Paragraph.</p> jQuery 代码: $("p").text("<b>Some</b> new text."); 结果: [ <p><b>Some</b> new text.</p> ] 值 val()val() 获得第一个匹配元素的当前值。 在 jQuery 1.2 中,可以返回任意元素的值了。包括select。如果多选,将返回一个数组,其包含所选的值。 -------------------------------------------------------------------------------- Get the content of the value attribute of the first matched element. In jQuery 1.2, a value is now returned for all elements, including selects. For multiple selects an array of values is returned. 返回值 String,Array 示例 获得单个select的值和多选select的值。 HTML 代码: <p></p><br/> <select id="single"> <option>Single</option> <option>Single2</option> </select> <select id="multiple" multiple="multiple"> <option selected="selected">Multiple</option> <option>Multiple2</option> <option selected="selected">Multiple3</option> </select> jQuery 代码: $("p").append( "<b>Single:</b> " + $("#single").val() + " <b>Multiple:</b> " + $("#multiple").val().join(", ") ); 结果: [ <p><b>Single:</b>Single<b>Multiple:</b>Multiple, Multiple3</p>] -------------------------------------------------------------------------------- 获取文本框中的值 HTML 代码: <input type="text" value="some text"/> jQuery 代码: $("input").val(); 结果: some text val(val)val(val) 设置每一个匹配元素的值。 在 jQuery 1.2, 这也可以为select元件赋值 -------------------------------------------------------------------------------- Set the value attribute of every matched element. In jQuery 1.2, this is also able to set the value of select elements, but selecting the appropriate options. 返回值 jQuery 参数 val (String) : 要设置的值。 示例 设定文本框的值 HTML 代码: <input type="text"/> jQuery 代码: $("input").val("hello world!"); val(val)val(val) check,select,radio等都能使用为之赋值 返回值 jQuery 参数 val (Array<String>) : 用于 check/select 的值 示例 设定一个select和一个多选的select的值 HTML 代码: <select id="single"> <option>Single</option> <option>Single2</option> </select> <select id="multiple" multiple="multiple"> <option selected="selected">Multiple</option> <option>Multiple2</option> <option selected="selected">Multiple3</option> </select><br/> <input type="checkbox" value="check1"/> check1 <input type="checkbox" value="check2"/> check2 <input type="radio" value="radio1"/> radio1 <input type="radio" value="radio2"/> radio2 jQuery 代码: $("#single").val("Single2"); $("#multiple").val(["Multiple2", "Multiple3"]); $("input").val(["check2", "radio1"]); 筛选过滤 eq(index)eq(index) 获取第N个元素 这个元素的位置是从0算起。 -------------------------------------------------------------------------------- Reduce the set of matched elements to a single element. The position of the element in the set of matched elements starts at 0 and goes to length - 1. 返回值 jQuery 参数 index (Integer) :元素在jQuery对象中的索引 示例 获取匹配的第二个元素 HTML 代码: <p> This is just a test.</p> <p> So is this</p> jQuery 代码: $("p").eq(1) 结果: [ <p> So is this</p> ] hasClass(class)hasClass(class) 检查当前的元素是否含有某个特定的类,如果有,则返回true。 这其实就是 is("." + class)。 -------------------------------------------------------------------------------- Checks the current selection against a class and returns true, if at least one element of the selection has the given class. This is an alternative to is("." + class). 返回值 Boolean 参数 class (String) : 用于匹配的类名 示例 给包含有某个类的元素进行一个动画。 HTML 代码: <div class="protected"></div><div></div> jQuery 代码: $("div").click(function(){ if ( $(this).hasClass("protected") ) $(this) .animate({ left: -10 }) .animate({ left: 10 }) .animate({ left: -10 }) .animate({ left: 10 }) .animate({ left: 0 }); }); filter(expr)filter(expr) 筛选出与指定表达式匹配的元素集合。 这个方法用于缩小匹配的范围。用逗号分隔多个表达式 -------------------------------------------------------------------------------- Removes all elements from the set of matched elements that do not match the specified expression(s). This method is used to narrow down the results of a search. Provide a comma-separated list of expressions to apply multiple filters at once. 返回值 jQuery 参数 expr (Expression) : 表达式 示例 保留带有select类的元素 HTML 代码: <p>Hello</p><p>Hello Again</p><p class="selected">And Again</p> jQuery 代码: $("p").filter(".selected") 结果: [ <p class="selected">And Again</p> ] -------------------------------------------------------------------------------- 保留第一个以及带有select类的元素 HTML 代码: <p>Hello</p><p>Hello Again</p><p class="selected">And Again</p> jQuery 代码: $("p").filter(".selected, :first") 结果: [ <p>Hello</p>, <p class="selected">And Again</p> ] filter(fn)filter(fn) 筛选出与指定函数返回值匹配的元素集合 这个函数内部将对每个对象计算一次 (正如 '$.each'). 如果调用的函数返回false则这个元素被删除,否则就会保留。 -------------------------------------------------------------------------------- Removes all elements from the set of matched elements that does not match the specified function. The function is called with a context equal to the current element (just like '$.each'). If the function returns false, then the element is removed - anything else and the element is kept. 返回值 jQuery 参数 fn (Function) : 传递进filter的函数 示例 保留子元素中不含有ol的元素。 HTML 代码: <p><ol><li>Hello</li></ol></p><p>How are you?</p> jQuery 代码: $("p").filter(function(index) { return $("ol", this).length == 0; }); 结果: [ <p>How are you?</p> ] is(expr)is(expr) 用一个表达式来检查当前选择的元素集合,如果其中至少有一个元素符合这个给定的表达式就返回true。 如果没有元素符合,或者表达式无效,都返回'false'. 'filter' 内部实际也是在调用这个函数,所以,filter()函数原有的规则在这里也适用。 -------------------------------------------------------------------------------- Checks the current selection against an expression and returns true, if at least one element of the selection fits the given expression. If no element fits, or the expression is not valid, then the response will be 'false'. 'filter' is used internally, therefore all rules that apply there apply here, as well. 返回值 Boolean 参数 expr (String) :用于筛选的表达式 示例 由于input元素的父元素是一个表单元素,所以返回true。 HTML 代码: <form><input type="checkbox" /></form> jQuery 代码: $("input[type='checkbox']").parent().is("form") 结果: true map(callback)map(callback) 将一组元素转换成其他数组(不论是否是元素数组) 你可以用这个函数来建立一个列表,不论是值、属性还是CSS样式,或者其他特别形式。这都可以用'$.map()'来方便的建立。 -------------------------------------------------------------------------------- Translate a set of elements into another set of values (which may, or may not, be elements). You could use this to build lists of values, attributes, css values - or even perform special, custom, selector transformations. This is provided as a convenience method for using '$.map()'. 返回值 jQuery 参数 callback (Function) : 给每个元素执行的函数 示例 把form中的每

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值