[英]How to call js script file in asp.net core Blazor
How to call js script file (app.js) in the section of @code
@code
部分如何调用js脚本文件(app.js)
<script src="~/js/app.js"></script>
<script src="~/js/app.js">
function indexSlider(){
alert(1);
}
@code{
protected override async Task OnAfterRenderAsync(bool firstRender)
{
if (!firstRender)
{
return;
}
await JSRuntime.InvokeAsync<string>("indexSlider");
}
}
If you want use .js file in blazor server app.如果您想在 blazor 服务器应用程序中使用 .js 文件。
1.create your .js file in wwwroot folder. 1.在 wwwroot 文件夹中创建您的 .js 文件。 Ex: Javascript.js:例如:Javascript.js:
window.JsInteropFunction = (ctrl) => {
var a = document.getElementById(ctrl);
return a;
};
2.refer that .js file in _Host.cshtml file(head tag). 2.在 _Host.cshtml 文件(head 标签)中引用该 .js 文件。
<head> <script src="~/Javascript.js"></script> </head>
3.inject IJSruntime in your razor component. 3.在你的razor组件中注入IJSruntime。
@inject IJSRuntime JSRuntime;
@code{
jsruntime.invokevoidasync("jsinteropfunction", new object[] { "sidebar" },true);
statehaschanged();
}
@inject IJSRuntime JSRuntime
@code{
IJSObjectReference module;
module = await JSRuntime.InvokeAsync<IJSObjectReference>("import","~/js/app.js");
await module.InvokeVoidAsync("indexSlider", null);}
this is how you can do it and in your js file define a function like this.这就是你可以做到的,在你的js文件中定义一个像这样的function。
export function indexSlider()
{ //do something};
Example JS code timer示例 JS 代码计时器
var clock;
var date;
function startTime(element) {
let timeString = new Date().toLocaleTimeString('en-US', { hour: 'numeric', hour12: true, minute: 'numeric', second: 'numeric'});
let dateString = new Date().toLocaleDateString('en-US', { dateStyle: 'full'});
element.innerHTML = dateString + " - " + timeString;
clock = setTimeout(startTime.bind(null, element), 1000);
}
function stopTime() {
clearTimeout(clock);
}
In your wwwroot
folder find index.html
在您的wwwroot
文件夹中找到index.html
<script src='js/yourJS.js'></script>
In your razor component or page在您的 razor 组件或页面中
@inject IJSRuntime jsRuntimeService
<div @ref='timeElement'></div>
@code
{
ElementReference timeElement;
protected overried async Task OnInitializedAsync()
{
await jsRuntimeService.InvokeVoidAsync("startTime", timeElement);
await jsRuntimeService.InvokeVoidAsync("Alertfunction");
}
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.