2016-12-06 59 views
0

我试图追加孩子上市,但我想要做的就是将它追加到数据价格排序的地方。jquery追加触发器大于那么

我的模板:

<ul> 
    <li data-price="18"></li> 
    <li data-price="27"></li> 
    <li data-price="28"></li> 
    <li data-price="31"></li> 
    <li data-price="99"></li> 
    <li data-price="101"></li> 
    <li data-price="191"></li> 
</ul> 

我的JS什么我试过到目前为止:

var template = '<li data-price="100"></li>'; 
$('ul').find('li').filter(function() { 
    return $(this).attr("data-price") > 99; 
}).after(template); 

因此,如果价格是100,应该按价格排序,在这种情况下价格被附加大于99但小于101,但我没有任何工作解决方案。

回答

0

我不确定这是否是最好的方式来做到这一点,它是否会一直工作,但它适用于您的问题。试试吧

var template = '<li data-price="100">100</li>'; 
 
var checkPrice = $(template).attr("data-price"); 
 
var appendBefore = $('ul li').filter(function(){ 
 
    return parseInt($(this).attr("data-price")) > checkPrice-1; 
 
})[0]; 
 
console.log(appendBefore); 
 
$(appendBefore).before(template);
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> 
 
<ul> 
 
    <li data-price="18">18</li> 
 
    <li data-price="27">27</li> 
 
    <li data-price="28">28</li> 
 
    <li data-price="31">31</li> 
 
    <li data-price="99">99</li> 
 
    <li data-price="101">101</li> 
 
    <li data-price="191">191</li> 
 
</ul>

+0

你的答案是伟大的,但你的解决方案仅IR价格-1现在起。但事实是,较低的价格可能会更小-50 – Sandra

0

检查,如果这是你所需要的:

https://jsfiddle.net/3er0da9c/

var template = '<li data-price="100"></li>'; 
var itemValue = parseInt($(template).attr('data-price')); //Getting value that we should compare 
var value, smaller = 0, smallerItem; //We will need those variables to know where to place our "template" 


smallerItem = $('ul > li:first-of-type'); //Set the smaller item in our list to be the first one. Change that if your list wont be always asc sorted 

$('ul > li').each(function(){ //run through the given list 
     value = parseInt($(this).attr('data-price')); 
     if ((itemValue == value) || (itemValue > value)){ //if the actual item is equal, put our item right after it. If the item is smaller then our number, we save it and keep running 
     smaller  = value; 
     smallerItem = $(this); 
     } 
}); 

if (smaller != 0) //This will happens when we have at least one item smaller then our number 
     smallerItem.after(template); 
else 
     smallerItem.before(template); //else, we add our number at top 
+0

@Sandra您是否测试过我的解决方案?它与负数工作,即时通讯只是好奇,知道它是否成功 –