热门关键字:
jquery > jquery教程 > jquery教程 > jQuery调整li元素顺序

jQuery调整li元素顺序

577
作者:管理员
发布时间:2020/3/3 14:50:02
评论数:0
转载请自觉注明原文:http://www.jq-school.com/Show.aspx?id=957

<!DOCTYPE html>
<html>
<head>
<meta charset=" utf-8">
<meta name="author" content="http://www.softwhy.com/" />
<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中。





如果您觉得本文的内容对您的学习有所帮助:支付鼓励



关键字:jQuery
友荐云推荐