简体   繁体   中英

how can I use jquery with yii2

I am new in Yii framework (version 2.0) and I want to add some jQuery code to my page:

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

This code will hide the div when I click on it, can I declare <script> in the view?

And how can I write this code in jQuery?

First suggest you to change ($this) to $(this) & try something like this.

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

You also can use View::POS_HEAD , View::POS_BEGIN & View::POS_READY instead of View::POS_END .

In Yii2 jQuery and other script files by default comes at the end of the page right before html closing tag. This is good for faster page loading.

So if you write jQuery code in the middle of your page there will be $ not defined error. To solve that you should write jQuery code inside window.onload event:

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

Try this , I hope this will help You

<?php

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

?>

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM