jquery追加触发器大的地方

时间:2016-12-06 14:45:39

标签: javascript jquery append prepend

我试图将孩子附加到列表中,但我想要做的是将其附加到按数据价格排序的地方。

我的模板:

<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,但我没有任何有效的解决方案。

2 个答案:

答案 0 :(得分: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>

答案 1 :(得分: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