问题描述:灵活使用jquery中的index方法

方法签名:index([selector|element])

用法概述:P1.index(P2)  //调用者P1可以为对象或集合

  1. 参数为空,返回P1[0]在父容器内的索引;
  2. 参数为字符串(即传入了一个选择器selector),返回P1[0]在P2的所有匹配中的索引,即只要传入字符串,就是在P2匹配的元素中查找P1[0];
  3. 参数为js对象或jquery对象(即传入了一个或一组element),则返回P2[0]在P1中的索引,即只要传入的是对象,就是在P1中查找P2[0];和传入字符串的情况正好相反;

使用实例:

<ul>
    <li class="foo">Outer1</li>
    <li>
        <ul>
            <li>1</li>
            <li id="ok" class="foo">2</li>
            <li>3</li>
            <li class="foo">4</li>
        </ul>
    </li>
    <li>Outer3</li>
</ul>
$("li").index("#ok");     //-1,找不到,因为是在匹配"#ok"的元素中查找$("li")[0]
$("li").index($("#ok"));
$("li").index(".foo");    //0//更多情况可自行测试和研究

jQuery源码: (推荐:)

// Determine the position of an element within
// the matched set of elements
index: function( elem ) {
    // No argument, return index in parent
    if ( !elem ) {
        return ( this[ 0 ] && this[ 0 ].parentNode ) ? this.first().prevAll().length : -1;
    }
    // index in selector
    if ( typeof elem === "string" ) {
        return jQuery.inArray( this[ 0 ], jQuery( elem ) );
    }
    // Locate the position of the desired element
    return jQuery.inArray(
        // If it receives a jQuery object, the first element is used
        elem.jquery ? elem[ 0 ] : elem, this );
}

最新文章

  1. JAVA 设计模式之策略模式
  2. 防火墙iptables
  3. 利用yeoman快速搭建React+webpack+es6脚手架
  4. Array.sort()方法
  5. php-引号中出现$
  6. 进度条,随机数---demo笔记【原创】
  7. Labeling Balls
  8. struts2 一个简洁的struts.xml
  9. Android actionbar 搜索框
  10. hadoop2集群环境搭建
  11. Hadoop HDFS 用java API 进行读写
  12. rabbitMQ学习1:消息队列介绍与rabbitmq安装使用
  13. mongoose根据_id更新,且如果数组中没有元素就添加
  14. [转载]C++之路起航——标准模板库(deque)
  15. e的故事.一个常数的传奇 (Eli Maor 著)
  16. MySQL学习----explain查看一条sql 的性能
  17. Hibernate 再接触 多对多单向双向关联
  18. while和if的区别
  19. 【C基础】之联合体
  20. 解决:Invalid character found in the request target.The valid characters are defined in RFC 7230 and RFC3986

热门文章

  1. POJ1177 Picture 线段树+离散化+扫描线
  2. POJ3087 Shuffle&#39;m Up 简单模拟
  3. [转]VPN服务器配置详解
  4. Selenium2Library系列 keywords 之 _SelectElementKeywords 之_get_select_list_options(self, select_list_or_locator)
  5. 树莓pi快速ssh【校园网】
  6. CentOS上安装MySQL
  7. 系统虚拟化学习笔记——PCI设备
  8. 使用Dom4j生成xml文件
  9. 我用的Linux命令
  10. hdoj 2098 分拆素数和