2016-12-06 46 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您是否測試過我的解決方案?它與負數工作,即時通訊只是好奇,知道它是否成功 –