[英]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. 我在飞行中创建了一个DIV,并希望根据其属性值在其他Div之间进行定位。
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. 我的代码在下面工作,但在某些时间点,新的div开始不按顺序排列。
example of out of sequence 1 2 2 3 4 5 4 无序的例子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/ 这是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. 你在循环中的两种情况都返回false,导致它在第一次迭代后中断。 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)
}
}
});
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.