2016-12-05 180 views
1

我创建了一个即时创建DIV,并希望根据其属性值在其他Div之间进行定位。基于属性值在另一个基础上插入元素

我想按顺序。

<div data-door="1">1</div> 
<div data-door="3">3</div> 
<div data-door="4">4</div> 
<div data-door="6">6</div> 

我的代码在下面的工作,但在某些点休息,新的div开始不顺序。出序列

<input id="txtValue" type="text" > 
<button id="addMe">Add</button> 
<div id="container"> 
    <div data-door="3">3</div> 
</div> 
$("#addMe").click(function(){ 
    var strValue = $("#txtValue").val() 
    var newDiv = '<div data-door="' + strValue + '">'+ strValue +'</div>' 

    //loop thru all divs with data-door 
    $('*[data-door]').each(function(){ 
     console.log($(this).attr("data-door")) 
     if ($(this).attr("data-door") >= strValue) { 

      $(this).prepend(newDiv) 
      return false; 
     } 
     else{ 
      $("#container").append(newDiv) 
      return false; 
     } 

    }); 

}); 

这里的

例子是的jsfiddle https://jsfiddle.net/czcz/1sg5gyqj/26/

我不能数字为什么它的顺序是

回答

2

太复杂了:

$("#addMe").click(function(){ 
 
\t var strValue = $("#txtValue").val(); 
 
\t var str = '<div data-door="' + strValue + '">'+ strValue +'</div>'; 
 
    var wrapper = $('#container'); 
 
    $(wrapper).append(str); 
 
    $('div[data-door]').sort(sortIt).appendTo(wrapper); 
 
}); 
 
    
 
function sortIt(a, b){ 
 
    return ($(b).data('door')) < ($(a).data('door')) ? 1 : -1;  
 
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script> 
 
<input id="txtValue" type="text" > 
 
<button id="addMe">Add</button> 
 

 
<div id="container"> 
 

 
</div>

+0

这很好。比我原来的短得多。谢谢! – causita

1

你在循环中都返回false,导致它在第一次迭代后中断。这工作:

$("#addMe").click(function(){ 
    var strValue = $("#txtValue").val(); 
    var str = '<div data-door="' + strValue + '">'+ strValue +'</div>'; 
    if($.trim($("#container").html())==''){ 
    $('#container').append(str); 
    } else { 
    //loop thru all divs with data-door 
    var added = false; 

    $('*[data-door]').each(function(){ 
     console.log($(this).attr("data-door")) 
     if ($(this).attr("data-door") >= strValue) { 
     $(this).prepend('<div data-door="' + strValue + '">'+ strValue +'</div>') 
     added = true; 
     return false; 
    }}); 

    if (!added) { 
     $("#container").append(str) 
    } 
    } 
}); 
+0

谢谢哥们。这工作。 – causita