zoukankan      html  css  js  c++  java
  • jQuery 复合选择器的几个例子

    <!-- 本文例子所引用的jQuery版本为 jQuery-1.8.3.min.js Author:博客园小dee -->

    一. 复合选择器对checkbox的相关操作

    1  <input type="checkbox" id="ckb_1"  /> 
    2  <input type="checkbox" id="ckb_2" disabled="true" /> 
    3  <input type="checkbox" id="ckb_3" /> 
    4  <input type="checkbox" id="ckb_4" /> 
    5  <input type="button" id="btn" value="点击">

    例.需要把类型为checkbox,同时"可用"的元素设置成"已选择"

    方法①使用属性过滤选择器 [type='checkbox'] 和 [disabled!=disabled]

    $("input[type='checkbox'][disabled!=disabled]").attr("checked",true);

    在这个复合选择器中,使用属性过滤选择器时"可用"元素的选择应使用 disabled!=disabled,而设置属性时可以使用 attr("checked",true)或attr("checked","checked")。

    注意:在Jquery1.6以后,建议在设置disabled和checked这些属性的时候使用prop()方法而不是用attr()方法。

     因此建议的写法:

    $("input[type='checkbox'][disabled!=disabled]").prop("checked",true);   //建议写法

    方法②使用表单选择器 :checkbox 和属性过滤选择器 [disabled!=disabled]

    $('input:checkbox[disabled!=disabled]').prop("checked",true);

    方法③使用表单选择器 :checkbox 和表单对象属性过滤选择器 :enabled

    $(':checkbox:enabled').prop("checked",true);

    方法④使用.each()遍历

    1  $("input[type=checkbox]").each(function(){
    2         
    3         if ($(this).attr("disabled") != "disabled") {
    4         
    5             $(this).prop("checked",true);
    6         }
    7     
    8  });

    在判断属性时attr()方法应该判断是"disabled"还是"enable",而不是false或true。

     建议的写法:

    1  $("input[type=checkbox]").each(function(){
    2          
    3          if ($(this).prop("disabled") == false) {
    4          
    5              $(this).prop("checked",true);
    6          }
    7      
    8  });

    二. 复合选择器的其他例子

    1 <ul>
    2     <li >第一行</li>
    3     <li class="showli">第二行</li>
    4     <li class="showli">第三行</li>
    5     <li>第四行</li>
    6     <li style="display:none">第五行</li>
    7     <li class="showli">第六行</li>
    8     <li>第七行</li>
    9 </ul>

    例. 把第一个class为showli的li元素背景设为红色

    $("ul li[class=showli]:eq(0)").css("background":"red");

    结果是'<li class="showli">第二行</li>'的背景变成了红色。使用了属性过滤选择器 [class=showli] 和基本过滤选择器 eq(0)

    例. 把第五个可见的li的背景设为红色

    $("ul li:visible:eq(4)").css({"display":"blaock","background":"red"});

    结果是'<li class="showli">第六行</li>'的背景变成了红色,display:block是为了检测隐藏的li是否会被:visible过滤,display:none下是看不到红色背景的。使用了可见性过滤选择器 :visible

    例.(比较绕的)把第二个class为showli的li后面可见的第二个li的背景设成红色

    $("ul li.showli:eq(1)").nextAll("li:visible:eq(1)").css({"display":"block","background":"red"});

    结果是'<li class="showli">第六行</li>'的背景变成了红色。

    作者:小dee
    说明:作者写博目的是记录开发过程,积累经验,便于以后工作参考。
    如需转载,请在文章页面保留此说明并且给出原文链接。谢谢!
  • 相关阅读:
    android studio 模拟器关机重启操作
    一个大小写引发的灾难 --碎片的最佳实践4.5章节
    安卓项目一直卡在Project setup: reading from cache
    Android Studio制作九宫格位图(Nine-patch)
    android studio添加依赖
    安卓模拟器emulator-5554[OFFLINE]
    GPS翻转周期
    Android Studio 可视化界面 (Design)和文本界面(Text)的切换
    全国-地区-邮政编码
    全国-省-市-编码
  • 原文地址:https://www.cnblogs.com/dee0912/p/3964200.html
Copyright © 2011-2022 走看看