title: 47-jQuery操作DOM
publish: true
文本主要内容
样式操作和类操作
作用:设置或获取元素的样式属性值。
样式操作
1、设置样式:
      $("div").css("background-color","red");
     $("div").css({"width":100,"height":100,"background-color":"pink"});
 
 
 
 
  | 
 
2、获取样式:
  alert($("div").css("width"));
 
  | 
 
举例如下:

类操作(className)
1、添加类样式:
$(selector).addClass("liItem");  
  | 
 
注意:此处类名不带点,所有类操作的方法类名都不带点。
2、移除类样式:
$(selector).removeClass("liItem");   $(selector).removeClass();          
  | 
 
3、判断有没有类样式:
$(selector).hasClass("liItem");   
  | 
 
此时,会返回true或false。jquery对象中,只要有一个带有指定类名的就是true,所有都不带才是false。
举例:
<!DOCTYPE html> <html> <head lang="en">     <meta charset="UTF-8">     <title></title>     <style>         div {             width: 100px;             height: 100px;             background-color: pink;         }
          .current {             background-color: red;         }     </style>     <script src="jquery-1.11.1.js"></script>     <script>         $(function () {             $("button").eq(0).click(function () {                                  $("div").addClass("current");                                  alert($("div").hasClass("current"));             });
              $("button").eq(1).click(function () {                                  $("div").removeClass("current");                                  alert($("div").hasClass("current"));             });                      })     </script> </head> <body> <button>添加</button> <button>删除</button> <div></div> <div></div> <div></div> <div class="current"></div> </body> </html>
 
   | 
 
4、切换类样式:
$(selector).toggleClass(“liItem”);    
   | 
 
解释:为指定元素切换类 className,该元素有类则移除,没有指定类则添加。
如果采用采用正常的思路实现上面这句话,代码是:
if($("div").hasClass("current")){          $("div").removeClass("current") }else{          $("div").addClass("current") }
  | 
 
现在有了toggleClass()方法,一行代码即可实现。
举例:
<!DOCTYPE html> <html> <head lang="en">     <meta charset="UTF-8">     <title></title>     <style>         div {             width: 100px;             height: 100px;             background-color: green;         }         .current {             background-color: red;         }     </style>     <script src="jquery-1.11.1.js"></script>     <script>         $(function () {             $("button").click(function () {                                                   $("div").toggleClass("current");             });         })     </script> </head> <body> <button>切换背景</button> <div></div> </body> </html>
   | 
 
实现的效果:

样式操作和类操作的比较
举例:addClass+removeClass
代码实现:
<!DOCTYPE html> <html> <head lang="en">     <meta charset="UTF-8">     <title></title>     <style type="text/css">         * {             margin: 0;             padding: 0;         }
          ul {             list-style: none;         }
          .wrapper {             width: 1000px;             height: 475px;             margin: 0 auto;             margin-top: 100px;         }
          .tab {             border: 1px solid #ddd;             border-bottom: 0;             height: 36px;             width: 320px;         }
          .tab li {             position: relative;             float: left;             width: 80px;             height: 34px;             line-height: 34px;             text-align: center;             cursor: pointer;             border-top: 4px solid #fff;         }
          .tab span {             position: absolute;             right: 0;             top: 10px;             background: #ddd;             width: 1px;             height: 14px;             overflow: hidden;         }
          .products {             width: 1002px;             border: 1px solid #ddd;             height: 476px;         }
          .products .main {             float: left;             display: none;         }
          .products .main.selected {             display: block;         }
          .tab li.active {             border-color: red;             border-bottom: 0;         }
      </style>     <script src="jquery-1.11.1.js"></script>     <script>         jQuery(window).ready(function () {                          $(".tab>li").mouseenter(function () {                                  $(this).addClass("active").siblings("li").removeClass("active");                                                   $(".products>div").eq($(this).index()).addClass("selected").siblings("div").removeClass("selected");             });         });     </script> </head> <body> <div class="wrapper">     <ul class="tab">         <li class="tab-item active">国际大牌<span>◆</span></li>         <li class="tab-item">国妆名牌<span>◆</span></li>         <li class="tab-item">清洁用品<span>◆</span></li>         <li class="tab-item">男士精品</li>     </ul>     <div class="products">         <div class="main selected">             <a href="###"><img src="images/guojidapai.jpg" alt=""/></a>         </div>         <div class="main">             <a href="###"><img src="images/guozhuangmingpin.jpg" alt=""/></a>         </div>         <div class="main">             <a href="###"><img src="images/qingjieyongpin.jpg" alt=""/></a>         </div>         <div class="main">             <a href="###"><img src="images/nanshijingpin.jpg" alt=""/></a>         </div>     </div> </div>
  </body> </html>
 
   | 
 
上方代码中,我们注意,tab栏和下方图片栏的index值,一一对应,这里用得很巧妙。
效果:

jQuery 的节点操作
动态创建元素
原生 js 有三种动态创建元素的方式。这里我们学一下 jQuery 动态创建元素。注意,创建的是  jQuery 对象。
方式一:
var $spanNode1 = $("<span>我是一个span元素</span>");  
  | 
 
此方法类似于 原生 js 中的document.createElement("标签名");
方式二:(推荐)
var node = $("#box").html("<li>我是li</li>");
  | 
 
此方法类似于 原生 js 中的innerHTML。
举例:
 console.log($("<li class='aaa'>我是li标签</li>"));
 
  $("ul").html("<li>我是html方法穿件出来的li标签</li>")
 
  | 
 
添加元素
jQuery 添加元素的方法非常多,最重要的方法是append()。格式如下:
 $(selector).append($node);   
 
  $(selector).append('<div></div>');  
 
 
  | 
 
作用:在被选元素内部的最后一个子元素(或内容)后面插入内容(存在或者创建出来的元素都可以)。
通俗的解释:在盒子里的最末尾添加元素。
举例:
<!DOCTYPE html> <html> <head lang="en">     <meta charset="UTF-8">     <title></title>     <script src="jquery-1.11.1.js"></script>     <script>         jQuery(document).ready(function () {             $("button").click(function () {                                  var jqNewLi = $("<li>我是jquery创建出来的li。用的是append方法添加</li>");
                                   $("ul").append(jqNewLi);                                  })         });     </script> </head> <body> <button>添加li</button>
  <ul>     <li>我是土著li</li> </ul>
  </body> </html>
   | 
 
效果:

其他的添加元素的方法:
方法2:
$(selector).appendTo(node);
   | 
 
作用:同append(),只不过是反着写的。
方法3:
$(selector).prepend(node);
   | 
 
作用:在元素的第一个子元素前面追加内容或节点。
方法4:
作用:在被选元素之后,作为兄弟元素插入内容或节点。
方法5:
$(selector).before(node);
   | 
 
作用:在被选元素之前,作为兄弟元素插入内容或节点。
清空元素
方式一:没有参数
$(selector).empty(); $(selector).html("");
   | 
 
解释:清空指定元素的所有子元素(光杆司令)。
方式二:
//
解释:“自杀” 。把自己以及所有的内部元素从文档中删除掉。
复制元素
格式:
复制的新元素 = $(selector).clone();
   | 
 
解释:复制$(selector)这个元素。是深层复制。
总结
推荐使用 html("<span></span>") 方法来创建元素或者 html("") 清空元素。
案例:选择水果
完整版代码:
<!DOCTYPE html> <html> <head lang="en">     <meta charset="UTF-8">     <title></title>     <style>         select {             width: 170px;             height: 240px;             font-size: 18px;             background-color: #a4ff34;         }     </style>     <script src="jquery-1.11.1.js"></script>     <script>         $(function () {
                                        $("button").eq(0).click(function () {                                  $("#sel2").append($("#sel1 option"));             });
                           $("button").eq(1).click(function () {                                  $("#sel1").append($("#sel2 option"));             });
                                                     $("button").eq(2).click(function () {                                  $("#sel2").append($("#sel1 option:selected"));             });
                           $("button").eq(3).click(function () {                                  $("#sel1").append($("#sel2 option:selected"));             });
          })     </script> </head> <body> <select id="sel1" size="10" multiple>     <option value="0">香蕉</option>     <option value="1">苹果</option>     <option value="2">鸭梨</option>     <option value="3">葡萄</option> </select> <button>>>></button> <button><<<</button> <button>></button> <button><</button> <select id="sel2" size="10" multiple>
  </select> </body> </html>
 
   | 
 
效果:

案例:动态添加表格项
代码如下:
<!DOCTYPE html> <html> <head lang="en">     <meta charset="UTF-8">     <title></title>     <style>         table {             border-collapse: collapse;             border-spacing: 0;             border: 1px solid #c0c0c0;         }
          th,         td {             border: 1px solid #d0d0d0;             color: #404060;             padding: 10px;         }
          th {             background-color: #09c;             font: bold 16px "微软雅黑";             color: #fff;         }
          td {             font: 14px "微软雅黑";         }
          tbody tr {             background-color: #f0f0f0;         }
          tbody tr:hover {             cursor: pointer;             background-color: #fafafa;         }     </style>     <script src="jquery-1.11.1.js"></script>     <script>         $(function () {                          var data = [{                 name: "博客园",                 url: "http://www.cnblogs.com/smyhvae/",                 type: "程序员的精神家园"             }, {                 name: "简书",                 url: "https://www.jianshu.com/u/4d2e6b4bf117",                 type: "写作平台"             }, {                 name: "百度",                 url: "https://www.baidu.com/",                 type: "你就知道"             }];
                                                                  
 
                           $("input").click(function () {                                  var str = "";                                  for(var i=0;i<data.length;i++){                     
                                                                str += "<tr><td>"+data[i].name+"</td><td>"+data[i].url+"</td><td>"+data[i].type+"</td></tr>";                 }
                                   $("#j_tbData").html(str);             })         })     </script> </head>
  <body> <input type="button" value="获取数据" id="j_btnGetData"/> <table>     <thead>     <tr>         <th>标题</th>         <th>地址</th>         <th>说明</th>     </tr>     </thead>     <tbody id="j_tbData">                              </tbody> </table> </body>
  </html>
 
   | 
 
实现的效果:

代码解释:每次生成字符串str之前,记得先把之前的str清空,不然每次点击按钮,都会继续添加表格项。
将上一个案例进一步提升:点击按钮,添加数据
暂略。
jQuery 设置和获取属性
jQuery 无法直接操作节点的属性和src等,我们需要借助attr()方法。下面介绍。
属性操作
(1)设置属性:
$(selector).attr("title", "生命壹号");
  | 
 
参数解释:第一个参数表示:要设置的属性名称。第二个参数表示:该属性名称对应的值。
(2)获取属性:
$(selector).attr("title");
  | 
 
参数为:要获取的属性的名称,返回指定属性对应的值。
总结:两个参数是给属性赋值,单个参数是获取属性值。
(3)移除属性:
$(selector).removeAttr("title");
  | 
 
参数为:要移除的属性的名称。
(4)form表单中的 prop()方法:
针对checked、selected、disabled属性,要使用 prop()方法,而不是其他的方法。
prop方法通常用来影响DOM元素的动态状态,而不是改变的HTML属性。例如:input和button的disabled特性,以及checkbox的checked特性。
总结:细节可以参考:http://api.jquery.com/prop/。
以上四项的代码演示:
<!DOCTYPE html> <html> <head lang="en">     <meta charset="UTF-8">     <title></title>     <style>         .aaa {             border: 1px solid red;         }     </style>     <script src="jquery-1.11.1.js"></script>     <script>         $(function () {                          var jqinp = $("input").eq(0);             var jqinp2 = $("input:checkbox");             var jqbtn = $("button");
              jqbtn.click(function () {                 
 
 
                                   jqinp.attr("title", 111);                 console.log(jqinp.attr("title"));
                  jqinp.attr("aaa", 111);                 console.log(jqinp.attr("aaa"));
                                   jqinp.attr("class", "aaa");                 console.log(jqinp.attr("class"));
                  jqinp.removeAttr("class");                 console.log(jqinp.attr("class"));
                                   jqinp2.prop("checked", true);
 
              });         })     </script> </head> <body> <button>绑定</button> <input type="text"/> <input type="checkbox"/>
  </body> </html>
   | 
 
效果:

案例:表格案例全选反选
完整版代码:
<!DOCTYPE html> <html>
  <head lang="en">     <meta charset="UTF-8">     <title></title>     <style>         * {             padding: 0;             margin: 0;         }
          .wrap {             width: 300px;             margin: 100px auto 0;         }
          table {             border-collapse: collapse;             border-spacing: 0;             border: 1px solid #c0c0c0;         }
          th,         td {             border: 1px solid #d0d0d0;             color: #404060;             padding: 10px;         }
          th {             background-color: #09c;             font: bold 16px "微软雅黑";             color: #fff;         }
          td {             font: 14px "微软雅黑";         }
          tbody tr {             background-color: #f0f0f0;         }
          tbody tr:hover {             cursor: pointer;             background-color: #fafafa;         }     </style>     <script src="jquery-1.11.1.js"></script>     <script>         $(function () {                          
 
                                        $("#j_cbAll").click(function () {                                  $("#j_tb input:checkbox").prop("checked", $(this).prop("checked"));             });
                                        $("#j_tb input:checkbox").click(function () {                                                   if ($("#j_tb input:checkbox").length === $("#j_tb input:checked").length) {                                          $("#j_cbAll").prop("checked", true);                 } else {                     $("#j_cbAll").prop("checked", false);                 }             });
 
          })     </script> </head>
  <body> <div class="wrap">     <table>         <thead>         <tr>             <th>                 <input type="checkbox" id="j_cbAll"/>             </th>             <th>课程名称</th>             <th>所属团队</th>         </tr>         </thead>         <tbody id="j_tb">         <tr>             <td>                 <input type="checkbox"/>             </td>             <td>JavaScript</td>             <td>千古壹号</td>         </tr>         <tr>             <td>                 <input type="checkbox"/>             </td>             <td>css</td>             <td>千古壹号</td>         </tr>         <tr>             <td>                 <input type="checkbox"/>             </td>             <td>html</td>             <td>千古壹号</td>         </tr>         <tr>             <td>                 <input type="checkbox"/>             </td>             <td>jQuery</td>             <td>千古壹号</td>         </tr>         </tbody>     </table> </div> </body>
  </html>
 
   | 
 
val()方法和 text()方法
作用:设置或返回 form 表单元素的value值,例如:input、select、textarea 的值。
作用:设置或获取匹配元素的文本内容。不带参数表示,会把所有匹配到的元素内容拼接为一个字符串,不同于其他获取操作。
$(selector).text("我是内容");
  | 
 
作用:设置的内容包含html标签,那么text()方法会把他们当作纯文本内容输出。
总结:
text() 不识别标签。
 
html() 识别标签。
 
举例:
<!DOCTYPE html> <html> <head lang="en">     <meta charset="UTF-8">     <title></title>     <script src="jquery-1.11.1.js"></script>     <script>         jQuery(document).ready(function () {                          console.log($("input").val());
              $("input").val("我是value()赋值的input内容");             console.log($("input").val());
              console.log("-----------------");
                           console.log($("div").text());             $("div").text("<li>我是text()赋值的</li>")             console.log($("div").text());
              console.log("-----------------");
                           console.log($("div").html());             $("div").html("<li>我是html()赋值的</li>");             console.log($("div").html());         })     </script> </head> <body> <input type="text" value="我是input中已存在的 value内容"/> <div>     <li>你好</li> </div> </body> </html>
   | 
 
打印结果:
