关于js转json问题。

我想把移动过的div转成一条json,但是放到.each里面会生成好多条json,不知道怎么弄?
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">  
<html>  
<head>
<meta charset="utf-8">  
  <title> New Document </title>  
  <script type="text/javascript" src="http://apps.bdimg.com/libs/jquery/2.1.1/jquery.min.js"></script>  
  <style type="text/css">  
/*模块拖拽*/  
.drag{position:absolute;
      width:100px;
      height:100px;
      border:1px solid #ddd;
      background:#FBF2BD;
      text-align:center;
      line-height:100px;
      padding:5px;
      top:100px;
      left:160px;
      cursor:move;
    }
      
.box{ width:900px;
      height:500px;
      background:#AAA;
      position:absolute;
      top:36px;
      left:50px;
    }  
    
    
</style>  
  
<script type="text/javascript">  
// 模块拖拽  
$(function(){  
var _move=false;//移动标记  
var _x,_y;//鼠标离控件左上角的相对位置
$(".drag").each(function(index) {
   $(this).text("机柜"+(index+1))//机柜编号
   $(this).mousedown(function(e){  
        _move=true;  
        _x=e.pageX-parseInt($(this).css("left"));  
        _y=e.pageY-parseInt($(this).css("top"));  
        $(this).fadeTo(20, 0.5);
        //点击后开始拖动并透明显示  
        }).mousemove(function(e){  
           
          if(_move){  
            var x=e.pageX-_x;//移动时根据鼠标位置计算控件左上角的绝对位置  
            var y=e.pageY-_y;
            var left=$(this).position().left;
            var top=$(this).position().top;
            var _left=$(".box").position().left;
            var _top=$(".box").position().top;
            $(this).css({top:y,left:x});//新位置
            var json={
                     Index:index+1,
                     X:x,
                     Y:y
                }
            var last=JSON.stringify(json);//转json
            
            console.log(last);// 
            
            
        }    
            
        }).mouseup(function(){
            
             
           _move=false;  
        $(this).fadeTo("fast", 1);//松开鼠标后停止移动并恢复成不透明  
      });    
 });                        
            
});           
                
</script>  
</head>  
<body>
<div class="box">
  
  <div class="drag"></div>
  <div class="drag" style="margin-left:100px;"></div>
  <div class="drag" style="margin-left:200px;"></div>  
  <div class="drag" style="margin-left:300px;"></div>  
  <div class="drag" style="margin-left:400px;"></div>  
  <div class="drag" style="margin-left:500px;"></div>
  
</div>             
</body>  
</html>         
阅读 2.5k
2 个回答
 var arr = [],
 
 var json={
      Index:index+1,
      X:x,
      Y:y
  }
  
 arr.push(json);
 console.log(JSON.stringify(arr))
  1. JSON.stringify()的输出是字符串而不是json(建议参考这里,补下json基础);

  2. mousemove是高频事件,会在单位时间里反复触发,你又没加防抖或者节流,把数据输出放这里,数据量明摆着是hold不住的;

  3. 产品上建议设计个按钮,提示用户手动触发保存操作,点击后再将数据ajax传到后台,成功后给用户一个提示;

  4. 顶部建议使用HTML5声明,即变为<!DOCTYPE html>

撰写回答
你尚未登录,登录后可以
  • 和开发者交流问题的细节
  • 关注并接收问题和回答的更新提醒
  • 参与内容的编辑和改进,让解决方法与时俱进
推荐问题