簡體   English   中英

如何在不破壞javascript代碼的情況下用javascript字符串換行?

[英]how to give a line break with the javascript string without breaking javascript code?

我需要在以下情況下在javascript中添加一個中斷。

<?php
$str_alert = "";
if(isset($case1)){
    $str_alert .= "have case1 \n";
}
if(isset($case2)){
    $str_alert .= "have case2 \n";
}
if(isset($case3)){
    $str_alert .= "have case3 \n";
}
if(!empty($str_alert)){
?>
<script type="text/javascript" >
$(document).ready(function(){
     alert("<?=$str_alert?>");
});
</script>

它打破了JavaScript代碼,並顯示錯誤

SyntaxError:未終止的字符串文字

請給我任何解決方案

在PHP中添加\\以轉義\\n 嘗試以下代碼

<?php
$str_alert = "";
if(isset($case1)){
    $str_alert .= "have case1 \\n";
}
if(isset($case2)){
    $str_alert .= "have case2 \\n";
}
if(isset($case3)){
    $str_alert .= "have case3 \\n";
}
if(!empty($str_alert)){
?>
<script type="text/javascript" >
$(document).ready(function(){
     alert("<?=$str_alert?>");
});
</script>

您需要用轉義字符表示不允許在JS字符串(如換行)中用作文字的字符。

由於JSON是一種基於JavaScript文字語法的數據格式,因此您可以使用PHP的json_encode函數將所有基本數據類型(字符串,數字,數組,關聯數組)轉換為具有所有正確轉義字符的JavaScript代碼。

默認情況下,它甚至會轉義/因此您可以安全地輸出字符串</script>

alert(<?=json_encode($str_alert);?>);

由於"將包含在JSON中,因此您不應該手動添加它們。

沒有轉義符(),JavaScript字符串不能跨換行符。 請參閱此問題以獲取詳細答案:

如何在JavaScript的多行代碼中中斷字符串?

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM