为了账号安全,请及时绑定邮箱和手机立即绑定

jQuery追加字母数字

jQuery追加字母数字

慕慕森 2022-10-27 16:52:52
我真的为此苦苦挣扎了一段时间,所以我猜也许 SO 知道解决方案。我创建了一个实时搜索(在您搜索产品 id 之后)显示一行...这样的产品(简化):<div id="78524" class="live_search_product">   <!-- productinformation here --></div>在此下方有一个产品列表,其中包含产品。这些产品按字母数字排序如下:<div class="products_wrapper">  <div id="78500">     <!-- productinformation here -->  </div>  <div id="78501">     <!-- productinformation here -->  </div>  (id 78524 should come here when clicked)  <div id="78526">    <!-- productinformation here -->  </div></div>我想要的是:当您单击.live_search_product产品时,它需要将自己置于正确的 id 升序“之间”,我无法弄清楚这一点,也看不到这背后的逻辑。你们能给我一个正确的方向吗?非常感谢!
查看完整描述

1 回答

?
富国沪深

TA贡献1790条经验 获得超9个赞

您可以获取 ID 列表,对其进行排序,然后确定应将新元素放置在哪个索引处,并将其插入到 element on 之后index - 1:


const $list = $('#product-list');

$('.live_search_product').on('click', function() {


  const $this = $(this);

  const thisId = +$this.attr('id');

  const ids = [];

  $list.find('div').each(function() {

    ids.push(+$(this).attr('id'));

  });

  ids.push(thisId);

  

  ids.sort(function(a, b) { return a - b; });

  

  const index = ids.findIndex(function(el) { return el === thisId; });

  $this.insertAfter($list.find('div').eq(index - 1));

});

<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>

<div id="78524" class="live_search_product">

   Product 78524 info product info product info [click me]

</div>


List:

<div id="product-list">

  <div id="78500">

     Product 78500 info product info product info

  </div>

  <div id="78501">

     Product 78501 info product info product info

  </div>


  (id 78524 should come here when clicked)


  <div id="78526">

     Product 78526 info product info product info

  </div>

</div>


查看完整回答
反对 回复 2022-10-27
  • 1 回答
  • 0 关注
  • 176 浏览
慕课专栏
更多

添加回答

举报

0/150
提交
取消
微信客服

购课补贴
联系客服咨询优惠详情

帮助反馈 APP下载

慕课网APP
您的移动学习伙伴

公众号

扫描二维码
关注慕课网微信公众号