【问题标题】:Encoding a string and display string output in Javascipt在 Javascript 中编码字符串并显示字符串输出
【发布时间】:2020-02-26 12:00:55
【问题描述】:

我正在编写一个对字符串进行编码的代码,它希望在 div 中显示编码后的字符串。但是,它什么也没显示。我可以知道我的代码有什么问题吗?谢谢。

HTML:

<div id="c"></div>

Javascript:

function encode() {
  var a = "abcde";
  a = unescape(a);
  var c = String.fromCharCode(a.charCodeAt(0) - a.length);
  for(var i = 1; i < a.length; i++){
    c += String.fromCharCode(a.charCodeAt(i) - c.charCodeAt(i - 1));
  }
  return c;
  document.write(c)
}

【问题讨论】:

    标签: javascript html escaping encode


    【解决方案1】:

    从函数返回后,您正在将输出写入文档。试试这样的:

    function encode (){
      var a = "abcde";
      a = unescape(a);
      var c = String.fromCharCode(a.charCodeAt(0) - a.length);
      for(var i=1; i<a.length; i++){
          c+=String.fromCharCode(a.charCodeAt(i) - c.charCodeAt(i-1));
      }
      return c;
    }
    
    document.getElementById("c").innerText = encode();
    &lt;div id="c"&gt;&lt;/div&gt;

    【讨论】:

      【解决方案2】:

      您正在调用document.write() 您的函数已经返回。因此,该行永远不会执行。

      要么:

      • return 移到函数末尾
      • 让调用代码捕获返回值并调用它们document.write()

      【讨论】:

      • 不用谢我。只需对有帮助的答案进行投票,然后在最能解决您的问题的答案上点击“接受”。
      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2013-11-01
      • 1970-01-01
      • 2017-03-26
      • 1970-01-01
      • 2012-06-20
      • 1970-01-01
      • 2015-01-30
      相关资源
      最近更新 更多