Home  >  Q&A  >  body text

Dynamic addition problem with lack of space between elements

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粉775788723P粉775788723180 days ago326

reply all(1)I'll reply

  • P粉384244473

    P粉3842444732024-04-03 11:28:03

    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>

    reply
    0
  • Cancelreply