使用CakePHP,可以通过将以下内容放在视图中来插入普通的JavaScript:
$this->Html->scriptStart(array('inline' => false));
echo 'alert("Hello world!");';
$this->Html->scriptEnd();
不幸的是,如果您有多个echo语句,则所有文本都会被压缩为1个长行。有没有办法拆分行并插入换行符?
我已经尝试在echo'd语句的末尾添加\ n无效。
我认为通过正确使用分号可以让JS在一行中正确运行,但这会带来痛苦的阅读和调试体验。
答案 0 :(得分:2)
如果你不需要,你可以尝试不把它放在PHP中:
<?php $this->Html->scriptStart(array('inline' => false)); ?>
alert("Hello world!");
alert("Hello world!");
<?php $this->Html->scriptEnd(); ?>
然后只使用普通的js格式。
或者,您可以使用PHP_EOL
来回显不在字符串文字内的换行符。
<?php
$this->Html->scriptStart(array('inline' => false));
echo 'alert("Hello world!");' . PHP_EOL;
echo 'alert("Hello world!");';
$this->Html->scriptEnd();
?>
答案 1 :(得分:0)
我不确定我是否正确理解了你的问题,但试图逃避你的\n
,因为php会在你的javascript轮流之前将其解释为普通字符串,例如:
$first = "This is first line\\n";
$both = $first . "This is second line";
答案 2 :(得分:0)
我最终通过使用Js-&gt;缓冲区来解决问题,如下所示:
echo $this->Js->buffer('$(\'<input type="button" id="instaSave" value="Save"/>\')
.click(function(){
$(this).val("Saving...");
$(this).parents("form:first").ajaxSubmit({
success: function(responseText, responseCode) {
$(".food").each(function(fIndex){
...
');