首页 > 解决方案 > 如何清空由javascript填充的div标签

问题描述

我有一个脚本,用户在输入框中输入文本,当他们在下面的 div (#Output) 中键入时,它会以不同的字体显示文本。

我的问题是,如果用户删除输入框中的文本,填充的 div 标签留下了所有非动态数据,当没有任何内容时,我怎么能完全清空 div(在这种情况下为#Output)输入。

<script>
$(document).ready(function(){
    $("#UpdateText").keyup(function(){
        // Getting the current value of textarea
        var currentText = $(this).val();
        // set font variables
        var text = "";
        var i;
        for (i = 1; i < 30; i++) {
        // Setting the font of Div content
            text += "<div>Font-" + i + " : <span id=\"fontResult\" style=\"font-family:Font-" + i + "\">" + currentText + "</span></div>";
        }
        $('#Output').html(text);
    });
    
});
</script>

  <div class="content">
      <label for="UpdateText">Enter the text you would like here, then select your font</label>
    <br />
    <textarea id="UpdateText" rows="1" cols="30" style="resize: none; text-align: center" placeholder="Type the name/word here..."></textarea>
    <br />
    <br />

    <div id="Output"></div>
    <!-- end .content -->
  </div>

标签: javascripthtml

解决方案


最快没有任何其他变化:

 $('#Output').html(currentText ? text : "");

$(document).ready(function() {
  $("#UpdateText").keyup(function() {
    // Getting the current value of textarea
    var currentText = $(this).val();
    // set font variables
    var text = "";
    var i;
    for (i = 1; i < 30; i++) {
      // Setting the font of Div content
      text += "<div>Font-" + i + " : <span id=\"fontResult\" style=\"font-family:Font-" + i + "\">" + currentText + "</span></div>";
    }
    $('#Output').html(currentText ? text : "");
  });

});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div class="content">
  <label for="UpdateText">Enter the text you would like here, then select your font</label>
  <br />
  <textarea id="UpdateText" rows="1" cols="30" style="resize: none; text-align: center" placeholder="Type the name/word here..."></textarea>
  <br />
  <br />

  <div id="Output"></div>
  <!-- end .content -->
</div>

将版本更新到 ES6 并且不对空字符串执行任何操作

$(function() {
  $("#UpdateText").on("input", function() {
    $('#Output').empty();
    // Getting the current value of textarea
    const currentText = $(this).val().trim();
    if (currentText) {
      // set font variables
      const text = [...Array(31).keys()].slice(1)
        .map(i => `<div>Font-${i}: <span id="fontResult" style="font-family:Font-${i}">${currentText}</span></div>`);
      $('#Output').html(text);
    }
  });
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div class="content">
  <label for="UpdateText">Enter the text you would like here, then select your font</label>
  <br />
  <textarea id="UpdateText" rows="1" cols="30" style="resize: none; text-align: center" placeholder="Type the name/word here..."></textarea>
  <br />
  <br />

  <div id="Output"></div>
  <!-- end .content -->
</div>


推荐阅读