如何将 jquery 与 yii2 一起使用


how can I use jquery with yii2

我是Yii框架(2.0版)的新手,我想在我的页面上添加一些jQuery代码:

$(document).ready(function(){
    $('div').click(function(){
        $(this).hide()
    });
});  

当我单击它时,此代码将隐藏div,我可以在视图中声明<script>吗?

我如何在jQuery中编写这段代码?

首先建议你把($this)改成$(this),然后尝试这样的事情。

$script = <<< JS
$(document).ready(function(){
    $('div').click(function(){
        $(this).hide()
    });
}); 
JS;
$this->registerJs($script, View::POS_END);

您也可以使用 View::POS_HEADView::POS_BEGIN & View::POS_READY 代替 View::POS_END

  • 参考

试试这个,希望对您有所帮助

<?php
$this->registerJs(' 
    $(document).ready(function(){
         $(''.classname'').hide();
});', 'yii'web'View::POS_READY);
?>

在 Yii2 中,jQuery 和其他脚本文件默认位于页面末尾的 html 结束标记之前。这有利于更快的页面加载。

因此,如果您在页面中间编写jQuery代码,则会出现$ not defined错误。要解决这个问题,你应该在事件中编写jQuery代码window.onload

window.onload=function(){
                        //your jQuery code here
                    };