我无法让 JavaScript 代码在 cakephp3 中工作。最初我想通过单击选项来隐藏/显示 div 部分。除了这个 js 函数之外,该项目运行良好。我在文件 (webroot/js/myjs.js) 中有 js 函数,并在布局中调用该文件,如下所示。我单击选项按钮来调用此函数来测试它,但没有得到任何输出。我不知道我还需要做什么,因为我被困住了。
http://book.cakephp.org/3.0/en/views/helpers/html.html#creating-inline-javascript-blocks
<?php
$options=array(0=>'Student',1=>'Tutor');
echo $this->Form->input('cancelledBy',
[ 'label'=>false, 'style'=>"margin:10px;", 'type' => 'radio', 'options' => $options,
'onclick'=>'hide()', 'value'=>0]);
?>
<div id="cancel" style="display: none;">Hello hidden content</div>
//myjs.js
<script type="text/javascript">
function hide()
{
alert('asd');
var e = document.getElementById("cancel");
if(e.style.display == 'block')
e.style.display = 'none';
else
e.style.display = 'block';
}
</script>
//layoutfile (which appears when i see the page source with the javascript function
<?php echo $this->Html->script(['myjs.js']); ?>
最佳答案
在您的 View 中使用此$this->Html->script('myjs', ['block' => 'scriptBottom']);
并添加此 <?= $this->fetch('scriptBottom') ?>
到您之前的布局 </body>
编辑
删除'type' => 'radio'
并将onclick事件更改为onchange
$options = array(0=>'Student',1=>'Tutor');
echo $this->Form->input('cancelledBy', [
'label' => false,
'style' => "margin:10px;",
'options' => $options,
'onchange' => 'hide()',
]);
关于选项按钮上的 JavaScript 在 cakephp3 中不起作用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41370973/