无法从 Blazor 调用 Javascript。在'window'找不到'startDataTable'



我试图使用Blazor和DataTables.net组件向表添加排序功能。只有以下语法允许我在Blazor中使用Javascript互操作:

datatable.js

window.methods = {
startDataTable: function () {
$(document).ready(function () {
$('#table').DataTable();
});
},
showAlert: function () {
alert("waht up");
}
}

当我从Blazor组件调用showAlert函数时,它被执行。但如果我使用startDataTable函数,什么都不会发生。是不是少了什么?

List.razor

@if (!@ToggleList)
{
<table id="table" data-toggle="table" class="table table-responsive" data-sortable="true">
<thead>
<tr>
<th>Key</th>
<th>State</th>
<th data-sortable="true">Graduates</th>
<th data-sortable="true">Exams</th>
<th data-sortable="true">Exams finished</th>
<th data-sortable="true">Percentage</th>
</tr>
</thead>
<tbody>
@foreach (var item in States)
{
<tr>
<td>@item.Icveie</td>
<td @onclick="() => showCz(item.Icveie)">@item.Cdesie</td>
<td>@item.Ucn</td>
<td>@item.Exa_pre</td>
<td>@item.Exa_acre</td>
<td>@item.Porc_acre</td>
</tr>
}
</tbody>
</table>
}
protected override async Task OnInitializedAsync()
{
await JSRuntime.InvokeVoidAsync("methods.showAlert");
}

Index.cshtml

<script src="https://code.jquery.com/jquery-3.2.1.slim.min.js" integrity="sha384-KJ3o2DKtIkvYIK3UENzmM7KCkRr/rE9/Qpg6aAZGJwFDMVNA/GpGFF93hXpG5KkN" crossorigin="anonymous"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/popper.js/1.12.9/umd/popper.min.js" integrity="sha384-ApNbgh9B+Y1QKtv3Rn7W3mgPxhU9K/ScQsAP7hUibX39j7fakFPskvXusvfa0b4Q" crossorigin="anonymous"></script>
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/4.0.0/js/bootstrap.min.js" integrity="sha384-JZR6Spejh4U02d8jOt6vLEHfe/JQGiRRSQQxSfFWpi1MquVdAyjUar5+76PVCmYl" crossorigin="anonymous"></script>
<script type="text/javascript" charset="utf8" src="https://cdn.datatables.net/1.10.23/js/jquery.dataTables.js"></script>
<script src="_framework/blazor.webassembly.js"></script>
<script src="../js/datatable.js"></script>

我正在使用Blazor与ASP。NET Core 3.1。我的意图是使用datatable.net组件向表添加额外的功能。有什么建议吗?

从理论上讲,我认为值得看一看OnAfterRenderAsync(bool firstrender)

根据我所读到的,JS是最后渲染的,因此不能在OnInitializedAsync中使用。

MS文档描述如下:

https://learn.microsoft.com/en us/aspnet/core/blazor/components/lifecycle?view=aspnetcore - 3.1 # after-component-render

从文档中,Use this stage to perform additional initialization steps using the rendered content, such as activating third-party JavaScript libraries that operate on the rendered DOM elements.

***免责声明,我不能让这个工作在我的应用程序。我只能让JS在渲染后的动作中工作,比如点击按钮。但这似乎是微软想让我们在页面加载时运行JS的地方。所以我只希望这能给你指明正确的方向。

注意:另外,尽量离开JS。Blazor应该有工具来做JS正在做的事情。

最新更新