【问题标题】:jquery append where trigger is bigger thenjquery追加触发器更大的地方
【发布时间】:2017-04-21 06:01:54
【问题描述】:

我正在尝试将孩子附加到列表中,但我想做的是将它附加到按数据价格排序的地方。

我的模板:

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

【问题讨论】:

    标签: javascript jquery append prepend


    【解决方案1】:

    我不确定这是否是最好的方法以及它是否总是有效,但它适用于您的问题。试试看

    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 的情况。但事实是,更低的价格甚至可以小-50
    【解决方案2】:

    检查是否是您需要的:

    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
    

    【讨论】:

    • @Sandra 你测试我的解决方案了吗?它适用于负数,我只是想知道它是否成功
    猜你喜欢
    • 2014-10-31
    • 2019-05-25
    • 1970-01-01
    • 2013-04-26
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多