本文介绍了将文档加载到Blazor中后,如何使javascript函数可用?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

不使用Blazor,

<script>
    $(document).ready(function () {
        alert('hello')
        // what you want to initialize
    });
</script>

使用Blazor,我是否只需将上面的脚本放在 wwwroot/index.html 中,并通过 OnInitializedAsync 方法从Blazor剃刀页面中调用它?

With Blazor, do I just put the above script in wwwroot/index.html and call it from Blazor razor page in OnInitializedAsync method?

推荐答案

在Blazor Server App中,您可以将脚本标签(在_Host.cshtml文件中)添加到JavaScript文件中,如下所示:

In Blazor Server App you can add a script tag (in _Host.cshtml file) to your JavaScript file like this:

 <script src="_framework/blazor.server.js"></script>
 <script src="exampleJsInterop.js"></script>

您的JS文件应放在wwwroot文件夹中

Your JS file should be placed in the wwwroot folder

您可以从OnAfterRender(Async)对中调用JavaScript函数,如以下代码片段所示:

And you can call your JavaScript functions from the pair OnAfterRender(Async) as the following code snippet demonstrates:

 @inject IJSRuntime JSRuntime

<div @ref="divElement">Text during render</div>

@code {
    private ElementReference divElement;

    protected override async Task OnAfterRenderAsync(bool firstRender)
    {
        if (firstRender)
        {
            await JSRuntime.InvokeVoidAsync(
                "exampleJsInterop.setElementText", divElement, "Text after render");
        }
    }
}

注意:由于Blazor Server应用程序通常是预呈现的,因此JavaScript尚不可用,因此您必须等到呈现应用程序后才能调用JavaScript函数.还要注意,上面的代码检查这是否是第一次呈现应用程序……这是您初始化JavaScript对象的地方.

Note: Since a Blazor Server app is usually prerendering, JavaScript is not yet available, so you have to wait until your app is rendered, and only then call JavaScript functions. Note also that the code above check if this is the first time the app is rendered...this is the place where you should initialize your JavaScript object.

注意:以上内容不适用于WebAssembly Apps,因为从一开始就可以使用JavaScript.

Note: The above is not applicable to WebAssembly Apps, as JavaScript is available from the very beginning.

在WebAssembly Apps中,您应该将引用JavaScript文件的标记放置在wwwroot/index.html中,如下所示:

In WebAssembly Apps you should place the tag that references your JavaScript file in the wwwroot/index.html, like the following:

<script src="_framework/blazor.webassembly.js"></script>
<script src="exampleJsInterop.js"></script>

请注意,您仍然需要从OnAfterRender(Async)对中调用JavaScript函数.

Note that you still need to call your JavaScript functions from the OnAfterRender(Async) pair.

我希望能对您有所帮助!如果您被卡住,请告诉我

I hope that helps! If you get stuck, let me know

这篇关于将文档加载到Blazor中后,如何使javascript函数可用?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

09-25 17:14