Jquery第三章 过滤选择器

123 阅读1分钟

一.基本过滤器

写法描述
$(‘p:first’)选取页面元素内的第一个p元素
$(‘p:last’)选取页面元素内的最后一个p元素
$(‘p:not(.select)’)选取选择器不是select的p元素
$(‘p:even’)选取索引是偶数的P元素(索引从0开始)
$(‘p:odd’)选取索引是奇数的p元素(索引从0开始)
$(‘p:eq(index)’)选取索引等于index的p元素(索引从0开始,索引支持负数)
$(‘p:gt(index)’)选取索引>index的p元素(索引从0开始)
$(‘p:lt(index)’)选取索引<index的p元素(索引从0开始)
$(‘:header’)选取标题元素h1~h6
$(‘:animated’)选取正在执行动画的元素
$(‘input:focus’)选取当前被焦点的元素
<body>
<p>第一个P</p>
<p id="select">第二个P</p>
<p>第三个P</p>
<h3>我是h3</h3>
<h4>我是h4</h4>
<input type="text" value="123">
<script type="text/javascript">
    $(function(){
        $('p:first').css('color','pink');
//     $('p').first().css('color','pink');
        $('p:last').css('color','orange');
//     $('p').last().css('color','orange');
        $('p:not(#select)').css('background','green');
//     $('p').not('#select').css('background','green');
        $('p:even').css('font-family','华文行楷');
        $('p:odd').css('font-family','隶书');
        $('p:eq(1)').css('color','red');
//     $('p').eq(1).css('color','red');
        $('p:gt(1)').css('width','80px');
        $('p:lt(1)').css('width','120px');
        $(':header').css('color','blue');//全局查找
        $('h4:header').css('color','peru');//限定了是h4
        $('input').focus();//设置页面刷新就激活焦点
        $('input:focus').css('color','deeppink')
//     :focus过滤器必须是网页初始状态就已经被激活的焦点元素,不能是通过鼠标点击或Tab键激活
    });
</script>
</body>

三.可见性过滤器

写法描述
$(‘:hidden’)选取所有不可见元素
$(‘:visible’)选取所有可见元素
hidden过滤器一般是包含样式为display:none。input表单类型为hidden
设置了visibility:hidden的元素,虽然其在物理上是不可见的,但却保留了物理空间,因此该算是可见元素
<body>
<div style="width:50px;height:50px;background:#ccc;visibility:hidden">我是一个div标签</div>
<div style="height:50px;background:#ccc;display:none;">div</div>
<input type="hidden" name="hidden">
<div></div><!--没有文本或子元素的标签,不算隐藏元素-->
<p>我是一个小小p标签</p>
<script type="text/javascript">
    $(function (){
//************************全局查找隐藏元素
        var count=$(':hidden');
        alert(count.size());//7
        for(var i=0;i<count.length;i++){
            alert(count[i].nodeName);
        }//HEAD  META  TITLE  SCRIPT  DIV INPUT SCRIPT
//************************指定查找隐藏元素
        alert($('div:hidden').size()+':'+$('div:hidden').get(0).nodeName);//1:DIV
        alert($('input:hidden').size()+':'+$('input:hidden').get(0).nodeName);//1:INPUT
//************************全局查找显示元素
        var visible=$(':visible');
        alert($(':visible').length);//5
        for(var i=0;i<visible.length;i++){
            document.write(visible[i].nodeName+'<br>');
        }//HTML  BODY  DIV  DIV  P
    });
</script>