【问题标题】:Why '\n' is not working with ServiceNow script? New lines not being created为什么 '\n' 不适用于 ServiceNow 脚本?未创建新行
【发布时间】:2019-01-29 07:12:37
【问题描述】:

我们尝试了'\n' 的几种变体,并尝试了'\r',但脚本不断返回这些行,或者在它们之间有空格,而不是实际的新行。这是底部两个问题的脚本:

(function(current, previous, gs, action) {
    var eqStr ='cmdb_ci=' + current.getValue('cmdb_ci');

//eqStr='short_description=' + current.getValue('short_description');
    //eqStr += '^description=' + current.getValue('description');

    eqStr +='^priority=' + current.getValue('priority');
    eqStr +='^sys_domain=' + current.getValue('sys_domain');
    eqStr +='^company=' + current.getValue('company');
    eqStr +='^justification=' + current.getValue('number')
        + '\n' + current.getValue('short_description')
        + '\n' + current.getValue('description') ;

【问题讨论】:

  • 它的 \n\r 不是 /n/r 而且,字符串最终会输出到哪里?如果它被注入到一个 DOM 元素中,你会得到你的结果,因为\n 不是在 HTML 中导致换行的方法,<br> 是。这些代码只有 JS 运行时才能理解。
  • @StephenP 您不应该像以前那样编辑/更改帖子的内容。您假设正斜杠是拼写错误,而实际上可能不是。如果您在问题中更正它们,您可能只是在不知情的情况下解决了问题。
  • @ScottMarcus 帖子标题和正文中的斜杠是 /n——但 code 中的斜杠是正确的反斜杠。总的来说,我同意你的看法,但在这种情况下,很明显是问题的输入有误,而不是代码。
  • 这个eqStr 字符串之后如何使用?在<div> / <p> 中,输入元素<textarea>?
  • 我不小心把 /n 放在了标题中,但是使用 \n 时代码是正确的。那么在这种情况下我该如何使用
    呢?

标签: javascript servicenow


【解决方案1】:

如果您要构建的字符串最终将被注入到 DOM 元素中,则必须使用负责解析 DOM 元素的 HTML 解析器熟悉的代码。 HTML 解析器不知道 JavaScript 字符串转义码,如下所示:

let output = "This is\na test.";
document.querySelector("div").innerHTML = output;

let output2 = "This is\nanother test.";
document.querySelector("p").textContent = output2;
<div></div>
<p></p>

对于将成为 DOM 元素的一部分的字符串,您需要使用 HTML 标签来创建换行符,&lt;br&gt;

let output = "This is<br>a test.";
// innerHTML invokes the parser to parse the supplied string:
document.querySelector("div").innerHTML = output;

let output2 = "This is<br>another test.";
// This won't produce the line break because textContent doesn't invoke the HTML
// parser. Insted, the actual text will be placed in the string.
document.querySelector("p").textContent = output2; 
<div></div>
<p></p>

【讨论】:

  • 嗨,斯科特,我们最终将它用于底部两行 - eqStr +='^justification=' + current.getValue('number') + "%0d%0a" + current.getValue ('short_description') + "%0d%0a"+ current.getValue('description') ;
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2011-09-20
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2021-10-20
相关资源
最近更新 更多