jQuery对于demo元素的上移、下移、删除操作等实现
今天给大家分享一个实用的jQuery技能:dom元素的操作;我们经常会去获取dom元素去实现交互效果,以及数据的操作。
首先复习一下jQuery DOM 元素方法:
- .get() 获得由选择器指定的Dom元素
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <title></title> <script src="https://code.jquery.com/jquery-1.11.3.js"></script> <style> .container{ background:#ccc; font-size:12px; margin:20 auto; width:600px; height:400px; } </style> </head> <body> <p>1</p> <p>2</p> <p>3</p> <p>4</p> <p>5</p> <button>点我</button> <div class="container"></div> <script type="text/javascript"> $(document).ready(function(){ $("button").click(function(){ x=$("p").get(0); $("div").text(x.nodeName + ": " + x.innerHTML); }); }); </script> </body> </html>
- .index() 返回指定元素相对于其他指定元素的index位置
<html> <head> <script type="text/javascript" src="/jquery/jquery.js"></script> <style> .container{ width:600px; height:800px; background:#f5f5f5; } </style> <script type="text/javascript"> $(document).ready(function(){ $("li").click(function(){ $('div.container').html("点击li的index值是:"+$(this).index()); }); }); </script> </head> <body> <p>点击列表项可获得其相对于同胞元素的 index 位置:</p> <ul> <li>Coffee</li> <li>Milk</li> <li>Soda</li> </ul> <div class="container"></div> </body> </html>
- .size() 返回被jQuery选择器匹配的元素的数量
<html> <head> <script type="text/javascript" src="/jquery/jquery.js"></script> <script type="text/javascript"> $(document).ready(function(){ $("button").click(function(){ $("h3").html("li元素的数目是:"+$("li").size()); }); }); </script> </head> <body> <button>输出 li 元素的数目</button> <ul> <li>Coffee</li> <li>Milk</li> <li>Soda</li> </ul> <h3>li元素的数目是:</h3> </body> </html>
- .toArray() 以数组的形式返回jQuery选择器匹配的元素。
<html> <head> <script type="text/javascript" src="/jquery/jquery.js"></script> <script type="text/javascript"> $(document).ready(function(){ $("button").click(function(){ x=$("li").toArray() for (i=0;i<x.length;i++) { $('p').append("</br>第"+ i +"个列表的值是:"+x[i].innerHTML+"</br>"); } }); }); </script> </head> <body> <button>输出每个列表项的值</button> <ul> <li>Coffee</li> <li>Milk</li> <li>Soda</li> </ul> <p>这里显示点击后的每一个列表的值</p> </body> </html>
二、dom操作必须掌握的方法:增加、删除、修改、更新
remove(),append(),before(),after(),
html(),text(),可以访问元素也可以修改元素;
优秀的人一直在路上,优秀的你一直在尝试写新bug