简体   繁体   中英

Can I wrap a class around an array element?

I have a group of checkboxes that are used for filtering called $('.filters input') .

I add these filters to an array:

  $('.filters input').each(function (counter, element) {
    if (element.checked) {
      $selectedFilters.push({
        name: element.name,
        class: element.value,
      });
    }
  })

In the next section I join the elements:

 if ($selectedFilters.length > 0) {
    $filters = $selectedFilters.map(function (elem) {
      return elem.class;
    }).join(', ');

    let $names = $selectedFilters.map(function (elem) {
      return elem.name;
    }).join(' ');

Then I output this text:

$('.filter-box__applied-filters').html(`<div class="btn btn-primary">${$names}</div>`);

But this adds each array item within the same div, how would I make it so each item appears in a new div?

Since $names is an array you have to loop over $names and append a new child to the $('.filter-box__applied-filters') element to create each filter separately in

$names.each(function(filterName){
   $('.filter-box__applied-filters').append(`<div class="btn btn-primary">`+filterName+`</div>`);
})

jquery documentation for .each

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM