2016-09-30 60 views
0

我一直在使用按钮获取仪表板,每个按钮将代表一台机器。这些按钮是根据Jquery结果生成的。在指定的列数添加后添加新行javascript

目前,我想在一行中添加10个按钮,然后继续将它们添加到新行中。另外,我的另一个问题是,我想改变按钮的颜色取决于ajax的结果。

我试过下面的代码,但它给了我作为一个结果,我已经附在下面的图像。

IMAGE:http://i68.tinypic.com/296oysw.png

(对不起,不能发布图片,因为我是新来的#1)

$(document).ready(function(){ 
    var d = new Date(); 
    var now = d.getTime() + 300; 
    var color; 
    var u = '/read/machines/' +{{userid}}; 
    $.ajax({ 
     url: u, 
     type: "GET", 
     dataType: 'json', 
     success: function(data) { 
     $.each(data, function(i, item) {  
      if (item.lastCommunication > now){ 
      color = "success"; 
      }else{ 
       color = "warning"; 
      } 
      if (i != 0 && i%10 == 0){ 
       $('<tr>').append(
       $('<td>').append(
        $('<button type="info" id="info" class="btn btn-'+color +' btn-lg" ontouchstart="touchAvailable=true; machineInfo('+item.id +');" onclick="if(!touchAvailable) machineInfo('+item.id +');">'+item.name+'</button>') 
         ) 
        ).appendTo('#body'); 
      }else{ 
      $('<td>').append(
        $('<button type="info" id="info" class="btn btn-'+color +' btn-lg" ontouchstart="touchAvailable=true; machineInfo('+item.id +');" onclick="if(!touchAvailable) machineInfo('+item.id +');">'+item.name+'</button>') 
        ).appendTo('#body'); 
      } 
     }); 
     } 
     }); 
    }); 
    </script> 

回答

0

我觉得在else分支展会td元素被追加到#body tr:last

if(i%10 == 0){ 
$('<tr>').appendTo('#body'); 
} 

$('<td>').append(BUTTON_CODE).appendTo('#body tr:last'); 
+0

Amow感谢您的回复,只是去尝试,但我得到这个结果: http://i68.tinypic.com/2el86j5.png – natilas12

+0

,如果你没有第一TR在#body开始,你应该改变代码 – amow

+0

你是完全正确的!现在它每行仅显示10个按钮,但是,它会添加两次新按钮,如下所示:http://i67.tinypic.com/2ngrdbc.png。另外,你知道为什么它不取决于jQuery中'lastCommunication'的值吗? – natilas12

0

尝试创建行第一....当你到第十项或最后一项附加行并创建新行(如果需要)

var $tr =$('<tr>') 
$.each(data, function(i, item) { 
    if (item.lastCommunication > now){ 
     color = "success"; 
    }else{ 
     color = "warning"; 
    } 
    if (i != 0 && i%10 == 0 || i==data.length-1){ 
     // 10th button or last button append row 
     $tr.append(
       $('<td>').append(
         $('<button type="info" id="info" class="btn btn-'+color +' btn-lg" ontouchstart="touchAvailable=true; machineInfo('+item.id +');" onclick="if(!touchAvailable) machineInfo('+item.id +');">'+item.name+'</button>') 
       ) 
     ).appendTo('#body'); 
     //create new row 
     if(i !== data.length-1){ 
      $tr =$('<tr>'); 
     } 
    }else{ 
     $('<td>').append(
       $('<button type="info" id="info" class="btn btn-'+color +' btn-lg" ontouchstart="touchAvailable=true; machineInfo('+item.id +');" onclick="if(!touchAvailable) machineInfo('+item.id +');">'+item.name+'</button>') 
     ).appendTo($tr); 
    } 
});