jQuery调整li元素顺序

快乐打工仔 分类:实例代码

本章节分享一段代码实例,它实现了挑战li元素顺序的功能。

代码实例如下:

<!DOCTYPE html>
<html> 
<head> 
<meta charset=" utf-8"> 
<meta name="author" content="http://www.pipipi.net/" /> 
<title>前端教程网</title>
<style type="text/css">
ul{
  list-style-type:none;
  float:left;
  margin-right:30px;
  background-color:Green;
  width:100px;
  height:100px;
  padding:0px;
}
li{
  margin-bottom:5px;
  background-color:Red;
  cursor:pointer;
  font-size:12px;
  height:25px;
}
</style>
<script src="http://libs.baidu.com/jquery/1.9.0/jquery.js"></script> 
<script type="text/javascript">
var json = [
  { "id": "1", "webName": "前端教程网", "Age": "3"},
  { "id": "2", "webName": "特效下载", "Age": "1"},
  { "id": "3", "webName": "腾讯", "Age": "15"},
  { "id": "4", "webName": "网易", "Age": "10"}
];
$(function(){
  var $topUl = $("#topul");
  var $bottomUl = $("#bottomul");
  for (var index = 0; index < json.length; index++) {
    $Li = $("<li>" + json[index].webName + "," + json[index].Age + "岁</li>");
    $Li.click(function () {
      if ($(this).parent().attr("id") == "topul") {
        $(this).appendTo($bottomUl); 
      }
      else {
        $(this).appendTo($topUl);
      }
    });
    $topUl.append($Li);
  }
});
</script>
</head>
<body>
<ul id="topul"></ul>
<ul id="bottomul"></ul>
</body>
</html>

上面的代码实现了我们的要求,下面介绍一下它的实现过程。

一.代码注释:

(1).var json = [],这是一个数组,里面存储我们需要的数据。

(2).$(function(){}),当文档结构完全加载完毕再去执行函数中的代码。

(3).var $topUl = $("#topul"),获取id属性值为topul的元素。

(4).var $bottomUl = $("#bottomul"),获取id属性值为bottomul的元素。

(5).for (var index = 0; index < json.length; index++) {},对数组进行遍历操作。

(6).$Li = $("<li>" + json[index].webName + "," + json[index].Age + "岁</li>"),创建li元素。

(7).$Li.click(function () {}),为li元素注册click事件处理函数。

(8).if ($(this).parent().attr("id") == "topul") {

  $(this).appendTo($bottomUl); 

},如果当前li元素的父元素的id属性值,那么就将当前li元素移动到id属性值为bottomUl的ul中。

(9).$topUl.append($Li),将创建的li元素添加到ul中。

二.相关阅读:

(1).parent()方法可以参阅jQuery parent()一章节。

(2).attr()方法可以参阅jQuery attr()一章节。

(3).appendTo()方法可以参阅jQuery appendTo()一章节。

(4).append()方法可以参阅jQuery append()一章节。

回复

我来回复
  • 暂无回复内容