JQuery 学习(一)

JQuery 核心
$ 和 $()

JQuery的绝大多数方法都是对象方法,但也存在部分的非对象方法,这部分被称之为核心方法。对象方法和核心方法的命名空间不同。具体如下所示

// 这是一个对象方法,它的命名空间为$.fn,它通常跟一个选择器;
$('h1').remove();  

// 这是一个核心方法,它的命名空间为$。它前面不跟选择器;
$.each()

​ 他们之间的区别如下

  > 1. 对象方法调用`JQuery`选择的方法在`$.fn`命名空间中,并自动接收并返回选择的`this`;
  > 2. 核心方法的命名空间为`$`,它通常是使用类型方法,不适用于选择;他们不会自动传递任何参数,他们的返回值也会不同;
  >
  > ****

$(document).ready()
window.onload()

当浏览器DOM文档与资源加载完毕后,会调用该方法。通常我们会在该方法中去定义操作DOM的函数。但是因为他要等所有的资源加载完毕,特别是图片资源,该方法的等待时间会比较长;

// 常规写法
window.onload = function(){
    console.log("window.onload");
}

// JQuery 写法
$(window).on('load',function(){
   console.log("window.onload"); 
});

$(document).ready(function(){})

JQuery提供了该方法,该方法在文档流加载完毕后就会执行,不需要等待资源加载。同时,相对于·window.onload()只能定义一次的弊端,·$(document).ready(function(){})可以定义多次;

// 常用的定义方式
$(document).ready(function(){
    $('h1').remove();
})

// 简易模式
$(function(){
    $('h1').remove();
})


避免命名空间冲突
JQuery库在其他库之后

方法1:使用别名

<script src='prototype.js'></script>
<script src='jquery.js'> </script>
<scrip>

// 通过定义新别名;
var $jquery = JQuery.noConflect();

// 此处的$jquery 代表的JQuery对象;
$jquert(document).ready(function(){
   $jquery("div").hide(); 
});

// 此处的$代表的原型含义document.getElementById()函数
window.onload = function(){
    // var mainEle = document.getElementById("main");
    var mainEle = $("main");
}
</scrip>

方法2:

<script src = 'prototype.js'></script>
<script src = 'jquery.js'>,/script>
<script>
    // 让JQuery至于无冲突模式;
    JQuery.noConnflect();
	// 在ready()函数中将$作为变量传入,则在ready函数中$代表了JQuery对象;
	JQuery(document).ready(function($){
       	// 大括号中$代表了JQuery Object;
        $("div").hide();
    });
	// 另一种方式书写
	(function($){
        $('div').hide();
    })(JQuery);
	

	// 在ready()函数外部,$代表了prototype.js中的原型含义;
	window.onload = function(){
        var mainEle = $("main");
    };    
</script>

JQuery库在其他库之前

​ 如果JQuery库包含在其他库之前,则$已经是其他库中的含义。这种情况下,需要使用JQuery全称代表JQuery函数对象;

<script src='jquery.js'></script>
<script src = 'prototype.js'></script>
<script>
    // 因为JQuery库在其他库加载之前,所以$符号已经代表其他含义,这里使用全称;
    JQuery(document).ready(function(){
    	JQuery("div").hide();
	});
	// $符号代表了prototype中的定义
	window.onload = function(){
        var mainEle = $('main');
    }
</script>


属性

.attr()方法既可以作为setter也可以作为getter,取决于传入的参数;

  <script>
        $(document).ready(function () {
            // 获取属性值
            var href = $('a').attr('href');
            // 设置多个属性值
            $('a').attr(
                {
                    href: "http://www.google.com",
                    title: "Google 一下"
                }
            );
            // 设置单个属性;
            $('a').attr('title', "Welcome to the BaiDu");
            // 验证属性值
            var title = $('a').attr('title');
        });
    </script>

选择元素
ID选择器
//选择某个ID元素 ,如,<div id='ID'>Google</div>
$('#ID');

类选择器
// 选择具备具体类名的元素, 如<div class='className'>Google</div>
$('.className');

属性选择器
// 选择具备某个属性的元素,如<a href='http://www.google.com'>Google</a>
$("a[href='http://www.google.com']");

CSS选择器
// 根据css选择器的符合格式选择元素
$('#classname div ul li.current');

列表选择器
// 列表选择器,各个条件中间用‘,’号分隔
$('div.clanssName,ul li #current');

伪选择器
// 选择claa=external a元素为父元素中的第一个元素
$('a.external:first')

// 选择id= myform 元素下所有的input 元素
$('#myForm :input');
// 选择所有可见的div元素;
$('div:visible');

// 选择除前三位的所有div元素
$('div;gt(2)');

// 选择当前动画的div元素
$('div:animated');


选择过滤
// 当选择完元素后,过滤部分元素

// 选择后,只留下拥有p子元素的元素。 has(),包含某TAG
$('div.foo').has('p');

// 选择后,只留下不包含class =bar子元素的元素. not() 不包含TAG
$('h1').not('.bar');

//选择后,过滤出class=current的元素.filter() 过滤出操作,不是过滤掉
$('ul li').fiter('.current');

// 选择后,选择第一个元素。first()代表第一个元素
$('ul li').first();

// 选择后,选择第六个元素。eq()代表某序列号的元素(序列号是从0开始计算)
$('ul li').eq(5)


选择表单元素

JQuery提供了几个伪选择器,可以帮助查找表单中的元素。这些特别有用。

:checked(选中)

:checked适用于选中的单选按钮,多选按钮以及元素中选中的部分;

<head>
<script>
        $(document).ready(function () {
    		// 该选择器将会选择 单选按钮,多选按钮,以及select中选择选中的选项;
            var checkedEle = $('form :checked');
            for (var i = 0; i < checkedEle.length; i++) {
                console.log(i + ":" + checkedEle.eq(i).val());
            }
        });
</script>

</head>

<body>

</body>
<form>
    <div>
        <select>
            <option selected>西游记</option>
            <option>红楼梦</option>
        </select>
    </div>

    <div>
        <input type="checkbox" name="大学" value="3" checked>大学
        <input type="checkbox" name="高中" value="2">高中
    </div>

    <div>
        <input type="radio" name="sex" value="man" checked>MAN
        <input type='radio' name='sex' value="women">WEMAN
    </div>
</form>

:disabled(禁用)

选中input具有disable属性的任何元素作为目标(select元素包含);


// 适用案例
// 先适用普通选择器选中一组选择列表,在把disabled部分挑选出来
$('input.cb').filter(':disable');


:enabled(可用)

选中不具有disabled属性的元素;


// 选中form中,可用的元素,父元素与子元素不互相理想,如<select>父元素为disabled不影响子元素。
$('form :enable');


:input(输入)

适用:input选择器选择所有的<input>,<textarea>,<select><button>元素

$('form :input');

:selected (选中)

适用:selected选择器定位<option>元素中 任何选定项;

$('form :selected');

:password (密码)
// 选择密码类型的所有元素
$("input :password");

// 相当于
$("input[type='password']")

:reset (重设)
// 选择所有的reset类型元素
$('input :reset');

// 相当于
$("input[type='reset']");

:radio(单选)
// 选择radio类型的所有元素
$('input :radio');

// 相当于
$("input[type='radio']");

:text(文本)
// 选择所有的文本输入元素
$('input :text');

// 相当于
$("input[type='text']");

:submit(提交)
// 选择提交类型的所有元素
$('input :submit,button :submit');

// 相当于
$("input[type='submit'],button[type='submit']");

:checkbox(多选)
// 选择复选框的所有元素
$('input :checkbox');

// 相当于
$("input[type='checkbox']");

:button(按钮)
// 选择按钮类型的所有按钮元素和元素
$('input :button');

// 相当于
$("input[type='button']");

:image( 图片)
// 选择所有的图片类型元素
$('input :image');

// 相当于
$("input[type='image']");

:file(文件)
// 选择所有的文件类型元素
$('input :file');

// 相当于
$("input[type='file']");


注意点
选择包含元素

一旦通过选择器选择元素后,$ fn将会返回JQuery Object。所以要查看选择结果是否包含有元素,请通过返回结果的长度去确认。而不要通过是否存在返回结果,因为就算选择后不包含元素,依然是存在JQuery对象的


// 在执行选择器选择后,要确认选择是否存在符合条件的元素;
var result = $('form :input');

// 下面的方法是正确的
if(result.length){
	//  存在结果
}

// 下面的方法是不正确的
 if(result){
 	// 就算符合条件元素为空,result依然不为空;
}

lt =$('form :input');


保存选择结果
  //保存选择结果,结果是JQuery对象
	var result = $('form :input');


使用选择
Access(Getters Settters)

获取和设置元素信息的方法

  • html() :获取或设置html内容;
  • text() : 设置或获取文本内容,html内容将被剥离;
  • attr() :设置或获取提供的属性值;
  • width() :以整形形式获取或设置选中第一个元素的宽度(px);
  • height() :以整形形式获取或设置选中第一个元素的高度(px);
  • position() :只是Getter方法。获取一个对象,其中包含选择中第一个元素相对于第一个定位祖先元素的位置;
  • val() :获取或设置表单中元素的值;

示例

  // 获取html()与text()与val()的区别
<head>
   <script>
        $(document).ready(function () {
            // 获取 
            console.log("text:" + $('.one').text());
            console.log("html:" + $('.one').html());
    		/**
    		* Google Welcome to the Google
    		* 
    		* Google <a href='http://www.google.com'>Welcome to the Google</a>
    		*/

            // 
            console.log("val:" + $('form :radio').filter(":checked").val());
            console.log("val:" + $('form :input').eq(1).val());
            console.log("val:" + $(':text').first().val());
    		/**
    		* val:man
    		* val:women
    		* val:I am the text
    		*/

        });
    </script>

</head>

<body>
    <div class="one">
        Google
        <a href="http://www.google.com">Welcom to the Google</a>
    </div>

    <div>
        <form>
            <input type='radio' name="sex" value="man" checked>Man
            <input type="radio" name='sex' value="women">Women
            <input type="text" value="I am the text" placeholder="Please input the text">
        </form>

    </div>

</body>

链式调用

JQuery 支持链式方法调用

// 链式方法调用
$('div')
	.find('ul')
	.find('#li')
	.first()
		.html("<a href='http://www.google.com'>Google</a>")
		.end();
	.find('#current')
		.text('Facebook');



操作元素
移动,复制和删除元素

api

  • insertBefore() :将元素作为兄弟元素插入参数元素的前面,并返回被插入元素的引用;
  • before() :在当前元素前方插入参数元素作为兄弟元素;
  • insertAfter() :将元素作为兄弟元素插入参数元素的后面,并返回被插入元素的引用;
  • after() :在当前元素后方插入参数元素作为兄弟元素;
  • apendTo() :将元素作为子元素插入参数元素子元素的最后,并返回被插入元素的引用;
  • apend() :在当前元素作为父元素,在其内部的最后位置插入参数元素作为子元素;
  • prependTo() :将元素作为子元素插入参数元素子元素的最前面,并返回被插入元素的引用;
  • prepend() :在当前元素作为父元素,在其内部的最初位置插入参数元素作为子元素;

在方法的选择上应该遵循1.方法的引用是属于插入元素还是被插入元素。2.是否需要持有被插入元素的引用。


克隆元素
// 克隆元素 
$('ul li:current').clone();

// 克隆元素,并且复制相关的数据和事件
$('ul li:current').clone(true);

删除元素

//把元素从页面中永久删除。
var divElement = $('div').remove();

//  如果需要持久保存数据和事件,用该方法,在元素恢复到页面后,同时保持数据与事件;
 $('span').detect();

// 让元素内部的html置空;
$("ul li").empty();


创建元素
// 创建元素
var newElement = $("<a href='http://www.google.com' title='google'>Google </a>");
var newElement2 = $('<a/>'{
  	href:"http://www.google.com",
  	'class':'google'
  });

// 创建元素后,不会主动添加到DOM上
$('ul li:current').append(newElement);
newElement2.prependTo($('ul li')eq(2));

// 一步到位
$('ul li')last().append("<a href='http://www.baidu.com'>Baidu</a>")




JQuery对象

虽然DOM元素提供了创建交互式网页所需要的所有功能,但他们可能很麻烦。JQuery对象包装这些元素以平滑这种体验,并使常见的任务变得容易。使用JQuery创建或选择元素时,结果将始终包装在新的JQuery对象中。如果情况需要本机的DOM元素,则可以通过get()方法和数组样式的下标来访问他们。


遍历对象

DOM关系如图

<body>
    <div class='grandparent'>
        <div class='parent'>
            <div class='child'>
                <span class="subchild"></span>
            </div>
        </div>
        <div class="surrogateParent1"></div>
        <div class="surrogateParent2"></div>
    </div>
    </div>
</body>

祖先
	// 选择父类(直接祖先类)[div.child]
	$('span.subchild').parent();

	// 选择所有的祖先[div.child,div.parent,div.grandparent]
	$('span.subchild').parents();

	// 选择祖先中符合条件的祖先[div.parent]
	$('span.subchild').parents('div.parent');
	
	// 选择祖先,知道符合条件为止(不包含符合条件)[div.child,div.parent]
	$('span.subchild').parentsUntil('div.grandparent');

	// 选择符合条件最近的唯一元素[div.child],包含自身;
	$('span.subchild').closest('div');

	// 因为包含自身[div.child];
	$('div.child').closest('div');


子孙
	// 所有的子孙[div.child,span.subchild]
	$('div.parent').children();
	
	// 所有符合条件的子孙[span.subchild]
	$('div.grandparent').children('span')
	
	// 寻找符合条件[div.child]
	$('div.grandparent').find('div.child');
	

兄弟
	
	// 前一个兄弟元素[]
	$('div.parent').prev();
	// 前一个兄弟元素[div.parent]
	$('div.surrogateParent1').prev();
	
	// 后一个兄弟元素[div.surrogateParent2]
	$('div.surrugateParent1'.next())

	// 所有的后续兄弟元素[div.surrogateParent1,div.surrogateParent2]
	$('div.parent').nextAll()
	
	// 所有的前驱兄弟元素[div.surogateParent1,div.parent]
	$('div.surrogateParent2').prevAll();

	//所有前驱兄弟中的第一个[div.parent]
	$('div.surrogateParent2').prevAll().first();

	// 所有后续兄弟中的最后一个[div.surrogateParent2]
	$('div.parent').nextAll().last();

	// 所有后续兄弟直到条件(不包括)[div.surrogateParent1]
	$('div.parent').nextUnit('div.surrogateParent2');

	//  所有的兄弟姐妹[div.parent,div.surrogateParent2]
	$('div.surrogateParent1').siblings();

CSS相关
css属性
    <script>
        $(document).ready(function () {
            // 设置css属性;
            $('span').first()
                .css(
                    {
                        fontSize: '24px',
                        fontColor: '#00ffe1',
                        width: '400px',
                        height: '400px',
                        backgroundColor: 'white',
                        textAlign: 'center'
                    }
                );
			// 获取css属性;
            console.log('fonstSize:' + $('.subchild').css('fontSize'));
            console.log('fontColor:' + $('.subchild').css('color'));
            console.log('width:' + $('.subchild').width());
            console.log('height:' + $('.subchild').height());
            console.log('bgcolor:' + $('.subchild').css('backgroundColor'));
            console.log('textAlign:' + $('.subchild').css('textAlign'));

        });

    </script>

需要注意的是在进行css属性的获取与设置的回收,对于css属性名称要用驼峰式写法;


class
<script>
      $(document).ready(function () {
        
          // 判断是否存在某些class:return true;
          console.log('hasClass:' + $('span').eq(0).hasClass('subchild'));

          // 添加新类:return true;
          $('.subchild').addClass('newclass');
          console.log("has new class:" + $('span').eq(0).hasClass('newclass'));

          // 移除类:return false;
          $('.subchild').removeClass('newclass');
          console.log("remove has new class:" + $('span').eq(0).hasClass('newclass'));

          // 切换类(没有就添加,有就删除):return true;
          $('.subchild').toggleClass('toggleClass');
          console.log("toggle has new class:" + $('span').eq(0).hasClass('toggleClass'));

          // 切换类(没有就添加,有就删除):return false;
          $('.subchild').toggleClass('toggleClass');
          console.log("toggle has new class:" + $('span').eq(0).hasClass('toggleClass'));

      });
  </script>


尺寸
      $(document).ready(function () {

          $('span').first().width('100px');
          var setWidth = $('span').eq(0).width();

          $('span').first().height('100px');
          var setHeight = $('span').first().height();

          console.log('newWidth:' + setWidth);
          console.log("newHeight:" + setHeight);

      });

位置
  $(document).ready(function () {
      	// 这里获取位置信息
         var position = $('.subchild').position();
      	// positon.left,position.top;
         console.log('position:' + JSON.stringify(position));
   });

数据方法

通常有关于与元素一起存储的元素的数据。在javascript 中通常用给DOM元素添加新属性的方式实现。但这种方式很容易会造成内存泄漏。所以JQuery提供一一套存储与元素相关数据的方法。

​ 任何类型的数据都可以存储在元素上。

例子: 在这里插入图片描述
​ 如果一次加载所有的数据,每个书目都有自己对应的数据。在用户点击对应的书目后,需要在下方的盒子中显示该数据对应的数据;

​ 在该需求中,将每个书目对应的数据存储在其对应的li元素上,点击该li时直接从该li中取出数据,显示在下方的盒子中;

  
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <meta http-equiv="X-UA-Compatible" content="ie=edge">
    <script src="../js/jquery-3.4.1.js"></script>
    <title>Document</title>

    <style>
        * {
            margin: 0px;
            padding: 0px;
            list-style: none;
        }

        .center {
            width: 1000px;
            height: 52px;
            margin: 0px auto;
            background-color: aquamarine;
        }

        ul {
            position: relative;
            left: 50%;
            margin-left: -200px;
        }

        ul li {
            width: 100px;
            font: normal 18px/52px "Microsoft YaHei", "Simsun";
            border: 1px solid white;
            text-align: center;
            float: left;
            background-color: wheat;
            color: white;
        }

        ul li:hover {
            background-color: red;
            color: black;
        }

        ul li.current {
            background-color: chartreuse;
            color: darkturquoise;
            font-size: 24px;
        }

        .outline {
            width: 1000px;
            height: 300px;
            font: 400 20px/40px "Simsun";
            color: red;
            margin: 10px auto;
            border: 1px solid black;
        }
    </style>
    <script>
        $(document).ready(function () {
        	// 数据
            var outline = ["一个男人与一群女人的故事", "一群男人的故事", "一个男人与一群动物的故事", "105个男人与三个女人的故事"];

            $('li')
                .each(function () {
                    // 获取对应的JQuery对象
                    var li = $(this);
                	// 存储数据
                    li.data('outline_data', outline[li.index()]);
                    li.on('click', function () {
                        console.log('onclick:' + li.index());
                        $('li').filter('.current').toggleClass('current');
                        li.addClass('current');
                        //  取出数据,显示在下方盒子中;
                        $('.outline').text(li.data('outline_data'));
                    });
                })
        });
    </script>

</head>

<body>

</body>
<div class="center">
    <ul>
        <li class="current">红楼梦</li>
        <li>三国演义</li>
        <li>西游记</li>
        <li>水浒传</li>
    </ul>
</div>
<div class="outline">
</div>

</html>

实用方法
$.trim() 去除空格
// 定义含有空格的字符串
var trimString = "      This is an string    ";
var newString  = $.trim(trimString);

$.each() 迭代数组和对象
// 遍历数组;
           $.each(['a', 'b', 'c', 'd', 'e', 'f', 'g'], function (index, value) {
               console.log(index + ":" + value);
           });
           // 遍历对象
           $.each({ 'name': "javascript", 'age': 23, 'sex': 1, 'nickName': 'js', 'address': 'en' }, function (key, value) {
               console.log(key + ":" + value);
           });

$.inArray()判断数组包含

如果不包含则返回-1,包含则返回index;

        $(document).ready(function () {
            var list = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10];
            // 包含则返回下标
            console.log('index:' + $.inArray(1, list));
            // 不包含则返回-1
            console.log('index:' + $.inArray(13, list));

        })

$.extend()属性覆盖

后续对象的属性更改第一个对象的属性;

        $(document).ready(function () {
            var one = {
                'name': 'zhangsan',
                'age': 12
            }

            var two = {
                'name': 'lisi'
            }

            var three = {
                'name': 'wangwu',
                'age': 23,
            }

			//  这里one最终的属性会跟three相同
            var newAnotherOne = $.extend(one, two, three);
            console.log('newAnotherOne:' + JSON.stringify(newAnotherOne));
            console.log('one:' + JSON.stringify(one));
            console.log('two:' + JSON.stringify(two));

            // 如果不想修改原来的属性,可以用{}空对象作为接受者;
            var newObj = $.extend({}, one, two, three);
            console.log('newObj:' + JSON.stringify(newObj));
            console.log('one:' + JSON.stringify(one));
            console.log('two:' + JSON.stringify(two));
        });

$.proxy()代理

返回在提供范围内运行的代理函数,将this传递函数内部的含义设置为第二个参数(确定上下文)。

       	//该方法作为window的成员方法
		function logContext() {
            console.log(this);
        }
		// 此处的上下文应该是window;
        logContext();
		
		// 定义对象;
        var contextObj = {
            'name': 'Object',
            'age': 12
        };

		// 返回上下文为contextObj的函数代理;
        var newFunction = $.proxy(logContext, contextObj);

		// 此处的打印应该是contextObj;
        newFunction();

​ 如果对象中存在方法,则可以直接通过将对象与方法名作为参数,获得代理函数;

       $(document).ready(function () {

           var contextObj = {
               'name': 'Object',
               'age': 12,
               'logContext': function () {
                   console.log(this);
               }
           };

           // 点击后运行logcontext的上下文是div.outline元素。
           $('div.outline').click(contextObj.logContext);

           // 通过proxy则锁定了该方法运行的上下文为contextObj对象;
           $('div.outline').click($.proxy(contextObj, 'logContext'));

       });

类型判断

请复制代码看输出;


        console.log('isArray:' + $.isArray([]));
        console.log('isNumber:' + $.isNumeric(3.1415245));
        console.log('isFunction:' + $.isFunction(function () { }));

        console.log('-----------------------------------------------');

        console.log('boolean:' + $.type(true));
        console.log('string:' + $.type("abcd"));
        console.log('number:' + $.type(111));
        console.log('function:' + $.type(function () { }));
        console.log('object:' + $.type({}));
        console.log('array:' + $.type([]));
        console.log('null:' + $.type(null));
        console.log('undifine:' + $.type(undefined));
        console.log('date:' + $.type(new Date()));
        console.log('error:' + $.type(new Error()));
        console.log('regexp:' + $.type(new RegExp('/text/')));

        console.log('-----------------------------------------------');

        console.log('isEmpty array:' + $.isEmptyObject([]));
        console.log('isEmpty obj:' + $.isEmptyObject({}));
        console.log('isEmpty null:' + $.isEmptyObject(null));
        console.log('isEmpty undefined:' + $.isEmptyObject(undefined));
        console.log('isEmpty function:' + $.isEmptyObject(function () { }));

        console.log('-----------------------------------------------');


index()方法解析

index方法存在四种签名。

无参数

假设有文档流如下 ,以下所有的文档操作均针对如下文档流。

<body>
    <div>
        <ul>
            <div id="header" class='test'></div>
            <li id='one'>one</li>
            <li id='two' class='test'>two</li>
            <li id="three">thead</li>
            <div id="footer" class="test"></div>
        </ul>
        <div id="last"></div>
    </div>
</body>

​ 没有参数情况下index()方法表示获取方法调用元素在其父元素中的位置下标。

    <script>
        // li[id='one'],默认情况下会取出第一个元素查看在父元素的位置 ==>1
        console.log('li:' + $('li').index());
		// li[id='one'] ==>1
        console.log('li first:' + $('li').first().index());
		// li[id='two'] ==>2;
        console.log('li eq(1):' + $('li').eq(1).index());
		// li[id='three'] ==>3
        console.log('li last:' + $('li').last().index());
		
		// div[class='header'] ==> 0
        console.log('div header:' + $('div.test').index());
    </script>

参数为字符串

参数为字符串情况下,先将字符串作为查询条件查询符合条件的JQuery对象,再在此JQuery对象列表中查找到调用index()方法的JQuery对象在此列表中的位置。总结经验,倒着看

参数为字符串情况下:

  1. 将字符串参数作为查询条件,获得符合条件的JQuery对象列表;
  2. 获取调用index()方法的JQuery对象,如果为JQuery对象列表,则取第一个,默认调用first()方法;
  3. 查看步骤2中的JQuery对象在步骤1中列表的下标,并返回。如果不存在则返回-1;
 <script>
        /**
         * 以下面的为例子,从后往前看逻辑
         * No1:将index()方法中的字符串参数做查询,获取JQusey 列表
         * $('div')==== [div,div[id='header'],div[id='footer'],div[id='last'] ]
         * No2:查看调用index方法的JQuery对象在上述列表的位置。如果调用者也是JQuery Object,则默认取第一个;
         * $('#last').first() = div[id='last'];
         * No3: 返回结果,No1中列表的下标;
        */
        var lastIndex = $('#last').index('div');
        console.log('lastIndex:' + lastIndex);

        /**
         * 
         * No1:[li[id='one'],li[id='two'],li[id='three']];
         * No2:li[id='three'];
         * No3:2;
        */
        var threeIndex = $('#three').index('li');
        console.log('threeIndex:' + threeIndex);


        /**
         *如果No1与No2 不存在交集的情况下会怎么样?
         * No1:[li[id='one'],li[id='two'],li[id='three']];
         * No2:div[id='last'];
         * No3:-1;
        */

        var reflectIndex = $('#last').index('li');
        console.log('reflextIndex:' + reflectIndex);
   </script>

参数为JQuery对象

​ 参数为JQuery对象为JQuery对象的情况正好跟参数为字符串相反。经验就是顺着看,具体逻辑步骤

  1. 先确认调用index()方法的JQuery对象(一般情况为列表);
  2. 再确认传入index()方法中的JQuery 对象,如果为列表,则取第一个;
  3. 返回步骤2中JQuery对象在步骤1中列表的下标,如果不存在,则返回-1;
    <script>
        /**
         * 参数为JQuery对象情况下,逻辑思路
         * No1:确认调用index()方法的JQuery 对象列表
         * $('li')==>[li[id='one'],li[id='two'],li[id='three']];
         * 
         * No2:确认传入的JQuery对象,如果存在多个,则取第一个
         * $('#two) ==>[li[id='two']];
         * 
         * No3:返回No2中Jquery对象在No1中JQuery对象列表的下标,如果不存在,则返回-1;
         * 
         * 
        */
        var twoIndex = $('li').index($('#two'));
        console.log('twoIdex:' + twoIndex);


        /**
         *No1:$('.test) ==>[div[id='header'],li[id='two'],div[id='footer']];
         *No2:$('li')==>[li[id='one'],li[id='two'],li[id='three']]==> first() ==>li[id='one'];
         *No2:不存在,返回-1;
        */

        var twoIndexAnother = $('.test').index($('li'));
        console.log('twoIndexAnother:' + twoIndexAnother);

    </script>

参数为DOM对象

参数为DOM对象跟参数为JQuery对象的参数完全一样。只不过内部需要调用$(DOM)方法转化成JQuery对象。

    <script>
        var twoEle = $('#two').get(0);
        var twoIndex = $('li').index(twoEle);
        console.log('twoIdex:' + twoIndex);
	</script>


参数为DOM对象

参数为DOM对象跟参数为JQuery对象的参数完全一样。只不过内部需要调用$(DOM)方法转化成JQuery对象。

    <script>
        var twoEle = $('#two').get(0);
        var twoIndex = $('li').index(twoEle);
        console.log('twoIdex:' + twoIndex);
	</script>


遇到的问题
禁用、启用表单元素
// 禁用表单元素
$('xxx').prop('disabled',false);
// 启用表单元素
$('xxx').prop('disabled',true);

取消、选中单选、多选输入按钮
// 取消按钮
$('XXX').prop('checked',false);
// 选中按钮
$('xxx').prop('checked',true);


  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值