【问题标题】:Jquery .html() is removing space between words [duplicate]Jquery .html() 正在删除单词之间的空格 [重复]
【发布时间】:2021-06-26 22:31:31
【问题描述】:

我正在使用 jQuery 的 .html() 属性来填充选择框。我有一些选择,我想在单词之间保留空格,即使不止一个空格。但是,无论我在option 中留下多少空格,它似乎都会将其修剪为一个空格。请查看随附的片段作为示例,其中我有 3 个带有多个空格的选择选项,但都解析为单个空格:

$("#testSelect").html(`
                       <option>a b</option> 
                       <option>a  b</option>
                       <option>a                       b</option>
                       `);
                       
$("#testSelect").on("change", function(){
  console.log(`The value in the select box right now is ${$("#testSelect").val()}`)

});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<select id="testSelect">
</select>

【问题讨论】:

    标签: javascript html jquery


    【解决方案1】:

    您可以使用.replaceAll 将所有空格替换为&amp;nbsp;

    $("#testSelect").html(`
                           <option>a b</option> 
                           <option>a  b</option>
                           <option>a                       b</option>
                           `.replaceAll(" ", "&nbsp;"));
    
    $("#testSelect").on("change", function() {
      console.log(`The value in the select box right now is ${$("#testSelect").val()}`)
    });
    <script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
    <select id="testSelect">
    </select>

    【讨论】:

      猜你喜欢
      • 2016-11-27
      • 2016-04-16
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2014-10-01
      • 2012-05-29
      • 2017-06-20
      相关资源
      最近更新 更多