如何在jQuery中推送、弹出和包装值

How to push, pop, and wrap values in jQuery?

本文关键字:包装 jQuery      更新时间:2024-05-10

我到处找,都找不出这个!

在一个页面上,我有一个链接,有一个特定的类(plmore)。在同一页上,我有一些div,其中有一个类(fcontainer)。类plmore的链接数将始终等于使用fcontainer类的div数。

我的问题:

我需要用使用plmore找到的链接包装具有fcontainer类的div

伪代码:
获取HREFS阵列
获取DIV IDS阵列
WRAP DIVS与HREFS

这就是我目前所拥有的:

<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<script>
  jQuery(document).ready(function($) {
    var hrefs = new Array();
    $('a.plmore').each(function() {
      hrefs.push($(this).find('a').attr('href'));
    });
    var features = new Array();
    $('fcontainer').each(function() {
      features.push($(this).find('div').attr('id'));
    });
    /* how does one pop from both arrays and wrap?? */
  });
</script>

你是说像

jQuery(function ($) {
    //find all the target anchor elements
    var $as = $('a.plmore');
    //find the div elements
    $('.fcontainer').each(function (idx) {
        //wrap the div at index idx using the href value of anchor element at index idx
        $(this).wrap($('<a/>', {
            href: $as.eq(idx).attr('href')
        }))
    });
});

演示:Fiddle