为什么我使用这个Javascript函数丢失边距

时间:2018-06-01 20:46:07

标签: javascript html bootstrap-4

我正在使用Bootstrap4我有一个多选和一个单独的div显示当前选择的一系列徽章。 (因为如果使用移动设备,则选择不显示当前选择的内容,它仅显示选择了多少项目)

  <div class="form-control mb-2" id="fieldsCompleteness" name="fieldsCompleteness">                                
  <span class="badge badge-secondary">
      Acoustic
  </span>
  <span class="badge badge-secondary">
      Album
  </span>
  <span class="badge badge-secondary">
      Sort Album Artist
  </span>
  </div>

当用户更改选择时,必须更新徽章,并使用此Javascript函数的cal来完成。

function getSelectValues(select, readonlylist)
{                             
      var result = '';
    var options = select && select.options;
    var opt;

    for (var i=0, iLen=options.length; i<iLen; i++)
    {
        opt = options[i];
        if (opt.selected)
        {
            result+='<span class="badge badge-secondary">' + opt.text + '</span>';
        }
    }
    readonlylist.innerHTML =result;
    return result;
}

这样可行,但每个徽章之间的边距消失。我不明白为什么因为它似乎只是替换现有的Html(一系列跨度)完全相同。因为我误解了innerHTML是如何工作的,它对外部div上定义的类有影响吗?

2 个答案:

答案 0 :(得分:2)

html中的空格(徽章文本之前)被渲染(并缩减为单个空格) - 通过添加空格,即可以在JS中实现相同的效果,即更改

'<span class="badge badge-secondary">' + opt.text + '</span>'

'<span class="badge badge-secondary"> ' + opt.text + '</span>'

答案 1 :(得分:0)

  //works as answered above
    result+='<span class="badge badge-secondary"> ' + opt.text + '</span>';

    //but it is better without spaces between the + + unless you are concatinating different data types
    result+='<span class="badge badge-secondary"> '+opt.text+'</span>';

    //or you could just create and re-use a new variable like ...
    var x=' '; // or x='&nbsp;'
    //then use like...
    somestring+=somewordVAR+x;
    //so on so fourth