【问题标题】:Using .html() to clear previous random string not working使用 .html() 清除以前的随机字符串不起作用
【发布时间】:2016-01-31 02:59:18
【问题描述】:

我正在编写一个简短的函数,它将长度相等的随机字符串附加到给定的单词。例如,如果您输入单词“hello”,它将返回一个 5 个字母长的随机字符串。

这部分按预期工作。但是,我使用$('output').html(""); 覆盖最后一个随机字符串。我之前已经将它用于其他功能,它按预期工作,但在这里没有。我尝试在函数周围移动它,看看它是否与函数的顺序有关,但它没有删除之前的随机字符串。

我做错了什么?

Fiddle here

HTML:

<input type="text" id="input">
<button id="button">Click Me</button>
<div id="output"></div>

JavaScript:

var text = "";
var possible = "abcdefghijklmnopqrstuvwxyz";
$(document).ready(function () {
    $('#button').on('click', function () {

        var value = ($('#input').val());
        for (i = 0; i < value.length; i++) {
            text += possible.charAt(Math.floor(Math.random() * possible.length));
        };
        $('#input').val("");
        $('#output').html("");
        $('#output').html(text);
    });
});

【问题讨论】:

    标签: javascript jquery string for-loop random


    【解决方案1】:

    您还需要重置变量text

    $('#button').on('click', function() {
       text = '';
       // your code 
    });
    

    Example

    或将text 变量从父范围移动到onlick 处理程序

    $('#button').on('click', function() {
       var text = '';
       // your code 
    });
    

    Example

    你也不需要

    $('#output').html("");
    

    因为你设置了内容

    $('#output').html(text);
    

    【讨论】:

      【解决方案2】:

      问题不在于.html() 部分。问题是你的 var text 永远不会被重置。

      供参考 - http://jsfiddle.net/oo5eLbpu/2/

      更新后的答案如下

      var possible = "abcdefghijklmnopqrstuvwxyz";
      $(document).ready(function() {
          $('#button').on('click', function() {
              var text = ""; // moved the variable inside the click handler
              var value = ($('#input').val());
              for (i = 0; i < value.length; i++) {
                  text += possible.charAt(Math.floor(Math.random() *
                      possible.length));
              };
              $('#input').val("");
              $('#output').html("");
              $('#output').html(text);  
          });
      });
      

      此外,您可以从代码中删除以下行

      $('#output').html("");
      

      因为它下面的行设置元素的内容。

      供参考 - http://jsfiddle.net/oo5eLbpu/4/

      文档 - http://api.jquery.com/html/

      【讨论】:

        【解决方案3】:

        试试 $('#output').empty();

        发件人:https://api.jquery.com/empty/

        【讨论】:

          猜你喜欢
          • 1970-01-01
          • 2016-02-25
          • 2012-01-02
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 2018-05-08
          • 2021-08-25
          • 1970-01-01
          相关资源
          最近更新 更多