【问题标题】:Javascript string concatenationJavascript字符串连接
【发布时间】:2013-04-05 21:58:46
【问题描述】:

字符串连接有问题。我正在进行一系列 ajax 调用,并根据结果构建一个表,其中每个元素都有一个引导弹出框字段。在这个领域,我想展示更多的细节。代码如下:

...initiate ajax post ...
... other parameters...
function(data){//function called on success
        var popoverContent = 'Sent: ';
        popoverContent = popoverContent.concat(JSON.stringify(obj.value));
        popoverContent = popoverContent.concat('\nReceived: ');
        popoverContent = popoverContent.concat(JSON.stringify(data.error));
        console.log(popoverContent);

... other processing ...
...building table...

'<td> <a class="btn large primary" rel="popover" data-content='+popoverContent+' data-original-title="Detailed description">'+outcome+'</a></td>'+ ...

...rest of the code ...

现在我的问题是,虽然在控制台中 popoverContent 包含我想以字符串形式显示的所有数据,但在弹出窗口中只有 Sent: 被显示。如果我使 popoverContent 等于任何其他连接的部分,它会显示该部分,但它不会显示整个内容。 我在这里错过了什么?

【问题讨论】:

  • .concat() 是一个用于连接两个数组而不是字符串的函数。
  • @DeckerWBrower - 不正确,还有一个String concat 方法
  • @MichaelGeary - 哦对不起我的错。出于明显的原因,我以前从未见过有人使用它。感谢您指出这一点
  • 不用担心,它实际上也让我感到意外! MDN 绝对不推荐。

标签: javascript twitter-bootstrap popover


【解决方案1】:

您可以使用 += 运算符来代替 console.log 调用之前的内容,这通常更易于阅读(尽管不是必需的),如下所示:

var popoverContent = 'Sent: ';
popoverContent += JSON.stringify(obj.value);
popoverContent += '\nReceived: ';
popoverContent += JSON.stringify(data.error);

然而,真正的问题在于您的实际 HTML 输出。你没有用 "s 包围结果。事实上,它也需要被转义。像:

... '<td>' +
  '<a class="btn large primary" rel="popover" data-content="' +
      popoverContent.replace(/&/g, '&amp;').replace(/"/g, '&quot;')
     .replace(/\n/g, '<br/>') +
    '" data-original-title="Detailed description">' +
    outcome +
  '</a>' +
'</td> + ...

【讨论】:

  • 您是否尝试按照我的建议更新内容?如果您的弹出内容周围没有“s”,则只会显示第一个单词(在这种情况下是“Sent:”)
  • 您的更新可以解决问题:D。另外如何插入新行?
  • 我不确定。我很了解 JS 和 HTML,而不是 Twitter-Bootstrap ......他们可能有自己的语法。如果他们没有任何现成的文档,我会尝试 \r\n、\n 或
  • 您的答案的第一部分有误。 .concat 调用与+= 一样有效。考虑一下这段代码:var s = 'a'; s = s.concat('b'); console.log(s); 打印'ab'。也许您提到的引用问题是实际问题?
  • 酷,刚刚看到你的更新。事实上,MDN 提到 += 可能比 .concat() 更快,所以另一个很好的理由使用它。只是帮助澄清建议与错误修复。 :-)
猜你喜欢
  • 1970-01-01
  • 2014-04-29
  • 2020-01-21
  • 2013-10-13
  • 1970-01-01
  • 2020-12-05
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多