Dynamic addition problem with lack of space between elements
P粉775788723
P粉775788723 2024-04-02 16:51:12
0
1
319

I have the following template in my markup.

<template id="unsequenced-template">
    <button type="button" class="btn btn-primary railcar"></button>
</template>

Then I insert it into my DOM like this.

// 在指定的目标之前,在无序列表中插入一个铁路车辆
function addSequenced(railcar, $target) {
    var $clone = $($('#unsequenced-template').html());
    $clone.attr('data-id', railcar.id);
    $clone.text(railcar.number);
    $clone.insertBefore($target);
    modified = true;
}

This method works, but there is no space between the inserted buttons. I even tried adding a space before $clone but had no effect. I also tried adding spaces to the template but that didn't work either.

Some buttons are added at the beginning. They are one per line, with spaces shown between the buttons. But how to show space between buttons inserted using JavaScript?

P粉775788723
P粉775788723

reply all(1)
P粉384244473

Use flexbox to collapse all whitespace and add gaps.

#btn-container {
  display: flex;
  flex-wrap: wrap;
  gap: 0.2em;
}

function addSequenced(railcar, $target) {
    var $clone = $($('#unsequenced-template').html());
    $clone.attr('data-id', railcar.id);
    $clone.text(railcar.number);
    $clone.insertBefore($target);
    modified = true;
}

let num = 4;
$("#add-btn").on("click", function(e) {
  addSequenced({
    id: num,
    number: num,
  }, $(this));
  num++;
});
#btn-container {
  display: flex;
  flex-wrap: wrap;
  gap: 0.2em;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<link href="https://cdn.jsdelivr.net/npm/bootstrap@5.2.3/dist/css/bootstrap.min.css" rel="stylesheet" integrity="sha384-rbsA2VBKQhggwzxH7pPCaAqO46MgnOM80zW1RWuH61DGLwZJEdK2Kadq2F9CUG65" crossorigin="anonymous">
<template id="unsequenced-template">
    <button type="button" class="btn btn-primary railcar"></button>
</template>
<div id="btn-container">
  <button type="button" class="btn btn-primary railcar">1</button>
  <button type="button" class="btn btn-primary railcar">2</button>
  <button type="button" class="btn btn-primary railcar">3</button>
  <button id="add-btn" type="button" class="btn btn-secondary">Add</button>
</div>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template
About us Disclaimer Sitemap
php.cn:Public welfare online PHP training,Help PHP learners grow quickly!