从函数输入到Javascript中插入带有换行符的单词


Insert words with newline character from function input to Javascript

我有一个条件。按钮输入中的pop函数的行1后面跟着换行Line2。当我点击javascript按钮时,它在控制台弹出错误"意外令牌非法"。

按钮pop()中的值是动态生成的。只有当我在输入文本中有一个新的行字符时,我才会得到这个错误。

<script type='text/javascript'>
function pop(valu)
{
alert("here"+valu);
document.getElementById('box').innnerHTML = valu;
}
</script>
<button onclick="pop('Line 1
Line 2')"> Click </button>
<textarea id='box'></textarea>

后端是PHP。

有没有办法在前景上实现这个?或者我是否应该对插入值进行任何更改?

我直接用换行符将值存储在DB中。

解决方案是在PHP端使用nl2br函数

nl2br($yournewlinestring); 
PHP将换行符转换为'n 的新行函数

但是在存储之前把你的html换行符转换成这样

$_POST['xyz'] = preg_replace('/(?:'r'n|['r'n])/', PHP_EOL, $_POST['xyz'] ); 

如果需要换行符,只需执行如下操作:

<?php $pop_variable = str_replace("'n", ''n', $pop_variable); ?>
<button onclick='pop("<?php echo htmlentities($pop_variable, ENT_QUOTES) ?>")' />

还记得运行htmlentities转义引号。

我确实认为这在HTML中做得太多了。将它存储在PHP数组中,然后将其json_encode(),可能更有益。这样,您就不必执行上述操作,也不必考虑在$pop_variable中出现"or"时会发生什么,并且如果您想添加更多按钮,也可以进行扩展(当然,这取决于您的用例)。

的例子:

<script>
function pop(valu) {
    // Should do some error checking to ensure pop_var is set
    document.getElementById('box').innnerHTML = pop_var[valu];
}
var pop_var = <?php echo json_encode(['button1' => "Line 1'nLine2", 'button1' => "Another Line 1'nAnother line with ' single quotes..."]);
</script>
<button onclick="pop('button1')">Click</button>
<button onclick="pop('button2')">Click</button>
<textarea id='box'></textarea>