在jquery就绪后,在_layout视图中,当页面加载时,从子视图自动调用javascript函数

auto invoke a javascript function from the child view, after jquery ready, in _layout view, when page loads

本文关键字:视图 函数 javascript 调用 加载 就绪 jquery layout      更新时间:2023-09-26

strongtext在我的ASP MVC 5应用程序中,我有一个(master-Jquery在此处加载_layout.cshtml和(child,我的函数在此处可排序,不加载tableView.cshtml

childtableView.cshtml中,我编写了需要在Jquery-Read$ready上调用的自定义JS函数。既然jquery已经加载在母版页中,当我的子页加载时,我如何附加我的函数(和第三部分插件)来调用它

如果可能的话,请在子视图加载/导航加载上共享一种模块化的方式来附加和初始化我的函数和子视图中的第三方插件,这样当主jquery函数加载时,它也会调用我的函数

_layout.cshtml

//  DOM ready is completed in master layout, I have custom JS plugin/code (sortable)
// in the child view that I need to load, when that loads
   $( document ).ready(function() {
      console.log( "Master layout ready, done" );
      });

TableView.cshtml

// in my tableView, that inherits layout from master, 
// how can I get this loaded when the page loads
  (function() {
    console.log( "How can I get child table plugin, loaded!" );
    })();

您应该使用@RenderSection()作为占位符来呈现视图中的内容

您的布局页面可能看起来像

<!DOCTYPE html>
<html>
<head>
  <meta charset="utf-8" />
  .....
  // Include common style sheets here
  @RenderSection("styles", false) // placeholder for styles
  @Scripts.Render("~/bundles/modernizr")
</head>
<body>
  ....
  @RenderBody()
  ....
  // Include all common scripts here
  @Scripts.Render("~/bundles/jquery") // include jquery first
  @RenderSection("scripts", required: false) // placeholder for page specific scripts
</body>
</html>

并且在视图中

@model YourModel
// html here
....
@section styles {
  <link href="~/Content/PageSpecificStyleSheet.css" rel="stylesheet" />
}
@section scripts {
  // Add page specific scripts and plugin files here
  @Scripts.Render("~/bundles/jqueryval")
  <script src="../../Scripts/MyScript.js" type="text/javascript"></script>
  ....
  <script type="text/javascript">
    // Other javascript code here
  </script>
}

注意@RenderSection("styles", false)<head>元素中,@RenderSection("scripts", required: false)紧接在关闭的</body>标记之前,这意味着视图中定义的任何脚本都将在页面元素加载后(以及在jquery文件之后)加载