问题
I want the exact target on which the click event has been triggered in ASP.NET Core blazor. Is this achievable?
回答1:
You can use @ref to get a reference to a DOM object, then pass it as a parameter to your handler function.
You can then pass it as a parameter to the JS Interop.
For example:
Counter.razor
@page "/counter"
@using Microsoft.JSInterop
@inject IJSRuntime JSRuntime
<h1>Counter</h1>
<p>Current count: @currentCount</p>
<p>Last button clicked: @lastButtonClicked</p>
<button @ref=button1 class="btn btn-primary" @onclick="@(()=>IncrementCount(@button1))">Click me</button>
<button @ref=button2 class="btn btn-primary" @onclick="@(()=>IncrementCount(@button2))">Click me</button>
@code {
private ElementReference button1;
private ElementReference button2;
private int currentCount = 0;
private string lastButtonClicked = "None";
private async void IncrementCount(ElementReference element)
{
currentCount++;
await JSRuntime.InvokeVoidAsync("setElementText", element, "I was clicked");
}
}
And make sure to add this script to Index.html
<script>
window.setElementText = (element, text) => { console.log(element); element.innerText = text; }
</script>
Reference: https://docs.microsoft.com/en-us/aspnet/core/blazor/javascript-interop?view=aspnetcore-3.1#detect-when-a-blazor-app-is-prerendering
来源:https://stackoverflow.com/questions/59213382/how-to-obtain-the-target-element-on-click-event-in-blazor