问题
Excuse me, everyone, how to enter Index.razor to automatically execute a js event
The carousel plugin used needs to automatically execute the following code
function(){
$("#banner").owlCarousel({
autoPlay : 3000,
paginationSpeed : 1000,
goToFirstSpeed : 2000,
singleItem : true,
autoHeight : true,
navigation: true,
transitionStyle: 'fade'
});
}
Such ineffective no longer should need to load the event in the child page _Host.cshtml
出现一个错误 Index.razor
出现Object reference not set to an instance of an object.
回答1:
Just create a JS interop function like that :
wwwroot/scripts/interop.js
window.carousel = {
play: (id, options) => {
$(id).owlCarousel(options);
}
}:
Launch it when your carousel at id is ready in your razor page or component.
Index.razor
@inject IJSRuntime _jsRuntime
<div id="banner"></div>
@code {
protected override async Task OnAfterRenderAsync(bool firstRender)
{
if (!firstRender)
{
return;
}
await _jsRuntime.InvokeVoidAsync("carousel.play", "#banner", new
{
autoPlay = 3000,
paginationSpeed = 1000,
goToFirstSpeed = 2000,
singleItem = true,
autoHeight = true,
navigation = true,
transitionStyle = "fade"
});
}
}
And launch your script in the _Host.cshtml
<script src="scripts/interop.js"></script>
来源:https://stackoverflow.com/questions/59134029/how-to-automatically-execute-a-js-event-non-click-event-when-dotnetcore-blazor