如何将onload()事件添加到laravel的@section('content')中

Is possible to do this? For example I have this code:

@section('content' onload='MyFunction')
  <!--PAGE CONTENT...-->
  <div>
   <h1>Something...</h1>
   <select name="sel"></select>
  </div>
@endsection

<script type="text/javascript">

  function MyFunction(){

   obj = document.forms[0].sel;

   for (i=0; i<23; i++) {

    //A similar condition to onload() event.

  }
</script>

Or is it wrong of me to do that so? I'm working in Laravel and PHP. Or maybe using a Jquery function similar to the function in javascript.

You must understand that @Section is a blade tag. Blade tags are processed inside PHP. Also, the blade syntax does not accept the parameter onload as you want.

Also, either on HTML/JS you can't use onload as you want.

You have two alternatives:

1 - Put a script tag after the section:

@section('content')
  <!--PAGE CONTENT...-->
  <div>
   <h1>Something...</h1>
   <select name="sel"></select>
  </div>
  <script>
    // Note that this function must have been declared before
    // this script tag, otherwise it will log an error:
    // "Uncaught ReferenceError: MyFunction is not defined"
    MyFunction(); 
  </script> 
@endsection

In this solution, the function will be called right after the browser loads this piece of html, but other parts of the html may not be loaded yet.

2 - Put a script tag watching for the load event on document:

<script>
    $(document).load(function() {
        MyFunction(); 
    });
</script>

The advantage of this method is that it will only be called after the entire page being loaded, so the order of the <script> tags doesn't matters (except that the jquery call must be after the jquery script tag.

Or, if you don't want to use jQuery and go for the native approach, you can use:

document.addEventListener("DOMContentLoaded", function(event) {
  // do your stuff here
});

IMHO is better if you divide HTML Markup and scripts using 2 sections eg:

 @section('content')
     <!--PAGE CONTENT...-->
     <div>
         <h1> Something ... </h1>
         <select name="sel"></select>
     </div>
     <script type="text/javascript">
     function MyFunction(){
         obj = document.forms[0].sel;
         for (i=0; i<23; i++) {
             //A similar condition to onload() event.
         }
     }     
    </script>
 @endsection
 @section('script')
     MyFunction();
     // every script here will run onload
 @endsection

and in your layout place both sections

 <main class="container">
      <section id="content">
           @yield('content')
      </section>
 </main>

 <script type="text/javascript">
        $(function(){
            @yield('script')
        });
 </script>