【问题标题】:Javascript / JQuery Append the return of a function in a concatenated stringJavascript / JQuery 在连接字符串中附加函数的返回
【发布时间】:2016-06-24 19:48:38
【问题描述】:

我有一个返回字符串的函数:

function buildCell(){
     var returnString = '';
     returnString += '<td>';
     returnString += 'Cell Contents';
     returnString += '</td>';
     return(returnString);
}

我有另一个函数应该调用第一个字符串并内联返回它的值:

function buildTable(){
    $('body').html(
         '<table>'
         +'<tr>'
         + buildCell()
         +'</tr>'
    )
}

我的表格没有单元格,单元格返回未定义。如何在第二个函数中正确连接第一个函数的返回?

编辑:我删除了分号,但仍然收到“未定义”。当我在第一个函数中放置警报时,我在警报中看到了正确的值,但在第二个函数中仍未定义。

【问题讨论】:

  • 您在 buildTable 函数中错误地放置了分号 > buildCell();
  • 我试过不带分号,但仍然不确定。
  • 你的意思是没有添加一个单元格?或者你期望 buildTable 返回 undefined 以外的东西?
  • 您的代码运行良好。问题出在其他地方。
  • 问题寻求调试帮助(“为什么这段代码不起作用?”) 必须包括所需的行为、特定问题或错误以及必要的最短代码在问题本身中重现它。没有明确问题陈述的问题对其他读者没有用处。 - 您的问题目前没有提供重现问题的代码。

标签: javascript jquery function concatenation


【解决方案1】:

您在 buildTable 函数中错误地放置了分号 > buildCell();

从此改变你的功能:

function buildTable(){
    $('body').html(
         '<table>'
         +'<tr>'
         + buildCell(); // <---
         +'</tr>'
    )
}

到这里:

function buildTable() {
    return $('body').html('<table>' + '<tr>' + buildCell() + '</tr>');
}

https://jsfiddle.net/k0ageq81/

function buildCell() {
  var returnString = '';
  returnString += '<td>';
  returnString += 'Cell Contents';
  returnString += '</td>';
  return returnString;
}

function buildTable() {
  return $('body').html('<table>' + '<tr>' + buildCell() + '</tr>');
}

buildTable();
&lt;script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"&gt;&lt;/script&gt;

【讨论】:

  • 您的 sn-p 有效,但在您在上面发布的代码中,此分号不正确且无法正常工作。
  • 你知道吗。你编辑了你的答案。以前你已经发布了这个。 “试试这个” function buildTable(){ $('body').html( '' +'' + buildCell() +''; //
  • 我确信您看到了编辑,因此感到困惑。
  • 仅供参考,您的编辑可以在这里看到。 stackoverflow.com/posts/38021127/revisions
  • 根据时间戳,我的编辑是在您发表评论前约 3 分钟进行的。
【解决方案2】:

这行得通:

  <body>
    <script>
      function buildCell() {
        var returnString = '';
        returnString += '<td>';
        returnString += 'Cell Contents';
        returnString += '</td>';
        return(returnString);
      }
      function buildTable(){
        $('body').html(
          '<table>'
          +'<tr>'
          + buildCell()
          +'</tr>'
        );
      }
      buildTable();
    </script>
  </body>

【讨论】:

    猜你喜欢
    • 2023-03-14
    • 2023-03-06
    • 2013-11-02
    • 2014-09-06
    • 2016-04-23
    • 2015-02-10
    • 1970-01-01
    • 2016-07-03
    相关资源
    最近更新 更多