菜鸟学习笔记——jQuery中.css(),.each(),.append(),.html()方法总结

来源:互联网 发布:com域名需要备案吗 编辑:程序博客网 时间:2024/06/08 18:54

1、$(selector).css()

1)$(selector).css(name),返回css的属性值。如:$("p").css("color"),返回p的color值;

2)$(selector).css(name,value),设置css属性。如:$("p").css("font-size","10px"),设置p的font-size属性值为10px;

3)$(selector).css({property:value,property:value,...}),设置多个css属性。如: $(“p”).css({"font-size":"10px","font-family":"Arail","padding":"3px"}),设置p的多个属性值;

4)$(selector).css(name,function(index,value){}),利用函数设置css的属性。如:$(”div“).css(”heigh“,function(index,value){return value*3;}),高度变为原来的三倍。

注:1)name均为属性名,value为属性值。

      2)$(selector).css(name,function(index,value){})中的value为原来的属性值,虽然有时候index和value可以同时缺省,但是若index或者value中有一个缺省,则不能

         得到想要的结果。如:有如下一段代码

          <html>
          <head>
          <script type="text/javascript" src="/jquery/jquery.js"></script>
          <script type="text/javascript">
          $(document).ready(function(){
                $("div").click(function() {
                     $(this).css(
                     "width", function(index,value) {return parseFloat(value) * 1.2;});});
          });
          </script>
          <style>
          div {width:100px; height:50px; background-color:red;}
          </style>
          </head>

          <body>
          <div>请点击这里</div>
          </body>
          </html>

          执行结果为,每点击一次,宽度就增加一次。但是当把"width", function(index,value) {return parseFloat(value) * 1.2;})中的index或者value省略掉,点击之

          后,firefox和IE之下会出现不同的状况。虽然width值都为0.但是firefox不显示背景色,IE会根据字体的宽度显示背景色。

      3).css()还可以这样使用。

           var obcss=({"font-size":"10px","font-family":"Arail","padding":"3px"});

           $(“p”).css(obcss);

2、$(selector).each()

1)$(selector).each(function(index,element){}),循环遍历选择器所匹配的元素,并为每个匹配元素执行相关函数,其中,element是当前元素,若在后面没有用到index和element,则可以缺省。如: $("li").each(function(){alert($(this).text())}),循环输出每个li中的text;

2)$.each(Array,function(index,value){}),循环遍历数组Array,并执行相关函数,其中index为数组索引,value为具体值。

3、$(selector).append()

1)$(selector).append(content),在所匹配的元素结束之前添加content,content可以是html标签,text等。如:有如下一个代码片段

       <div class=container>

           <div class=inner>Hello!</div>

          <div class=inner>Goodbye</div>

       </div>

   当执行代码$(".inner").append("<p>Test</p>")之后,会得到

       <div class=container>

           <div class=inner>

               Hello!

              <p>Test</p>

           </div>

          <div class=inner>

               Goodbye

              <p>Test</p>

           </div>

       </div>

   即,在inner所匹配的元素(每个<div>)结束前,添加代码<p>Test</p>

2)$(selector).append(function(index,html)),与之前的几种方法中的用法类似。

4、$(selector).html()

1)$(selector).html(),返回第一个匹配元素的内容;

2)$(selector).html(content),设置所匹配元素的内容,覆盖原有值;

3)$(selector).html(function(index,oldcontent){}).

注:content中若想添加多个样式,每个属性之间用分号(;)分隔。如:

      $("p").html(<div class=name><div style='color:#d3d3d3';'font-size:10px'>Hello!</div></div>)

原创粉丝点击