简体   繁体   中英

insert element before another based on attribute value

I create a DIV on the fly and want to position between other Div's it based on their attribute value.

I would like to have it in sequence.

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

My code below works but at certain point breaks and the new div starts going out of sequence.

example of out of sequence 1 2 2 3 4 5 4

<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; 
        }

    });

});

Here is the JSFiddle https://jsfiddle.net/czcz/1sg5gyqj/26/

I can't figure why is it going of of sequence

Too complicated:

 $("#addMe").click(function(){ var strValue = $("#txtValue").val(); 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> 

You're returning false in both cases in your loop, causing it to break after the first iteration. This works:

$("#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)
    }
  }
});

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM