查看源代码时如何让代码在单行中?

how can I get the code to be in single line when viewing the source code?

我正在尝试创建一个动态添加输入的按钮,因为我使用的是 Zend 框架,所以我使用此方法从表单文件中获取输入:<?php echo $this->formm->getElement('refA'); ?>

但我收到此错误:未捕获的语法错误:意外的标识符

并且该添加按钮的 jquery 函数是:

$(document).ready(function (){
    var j = "<?php echo $this->formm->getElement('refA'); ?>";
    $("#add-more").click(function(){   
        $(".row").append(j);
    });
});

当我点击那个错误时,它会告诉我错误在哪里,它似乎使用了:

$(document).ready(function (){
    var j = "<label for="refA" class="optional">Article:</label>
             <select name="refA" id="refA" class="form-control">
               <option value="test1" label="test1">test1</option>
             </select>";
    $("#add-more").click(function(){   
        $(".row").append(j);
    });  
});

是否可以在单行中生成代码以便让按钮起作用?

看起来这是一个引用问题 - PHP 插入的数据有双引号,它会不断终止您的字符串。尝试将其用单引号引起来 - 对 refA:

进行转义

$(document).ready(function (){
    var j = '<?php echo $this->formm->getElement(\'refA\'); ?>';
    $("#add-more").click(function(){   
        $(".row").append(j);
    });
});

好的,在进行更多挖掘之后,您需要在它之前取出那些引号和空格。不幸的是,我不是 PHP 人 - 所以我希望语法是正确的 - 这个想法是从 refA 获取数据并将其存储在 $message - 然后去掉任何空格并转义任何引号,然后将值回显为 'j':

$(document).ready(function (){
   var j = '<?php $message = $this->formm->getElement("refA"); $message = preg_replace("/\r?\n/", "\n", addslashes($message));echo $message?>'
   $("#add-more").click(function(){   
       $(".row").append(j);
   });
});

PHP 方法在这里找到: https://www.the-art-of-web.com/php/javascript-escape/

另一个可以完全解决这个问题的选项是使用 es6 - template-strings (back-ticks)


$(document).ready(function (){
    var j = `<?php echo $this->formm->getElement("refA"); ?>`;
    $("#add-more").click(function(){   
        $(".row").append(j);
    });
});

大多数现代浏览器都会原生处理 es6 Template Strings

正如 Kyle 所说,您遇到了引用问题。但是,与他所说的不同,引号 inside PHP 标签 不能 转义,因为它们是在服务器端呈现的。

这应该可以解决问题:

window.onload = function() {
    $(document).ready(function (){
        var j = '<?php echo  preg_replace("/\r|\n/", "", $this->formm->getElement('refA')); ?>';
        $("#add-more").click(function(){   
            $(".row").append(j);
        });
    });
}

编辑:查看您的屏幕截图和其他评论,您似乎试图在加载前访问 jQuery ($)(我想您正在布局末尾加载所有 JS 依赖项)。 由于你不能在 JS 文件中使用 PHP 代码,你有两个选择:

  1. 您在模板 (ajouter.phtml) 中创建一个 JS 变量,例如 var inputTemplate = <?php echo preg_replace(....);?>;,并在您的 JS 文件中使用该变量
  2. 您确保 that JS 片段仅在页面完全加载时执行(因此使用 window.onload = function(){}

就个人而言,我建议您选择第一个选项。在 phtml 中插入 JS 代码在概念上是错误的,因为如果您以某种方式决定不再使用 jQuery,您将不必进入所有模板来查找这些片段。