[英]Blazor execute C# and JS function in one button onclick event
I have a button, which executes a JS function:我有一个按钮,它执行一个 JS function:
<button class="btn-orange btn" onclick="expand(this.closest('.profile'))">JavaScript</button>
And a button, which executes C# and switches icons depending on a bool:还有一个按钮,它执行 C# 并根据布尔值切换图标:
<button class="btn-orange btn"
@onclick="@(() =>
{
if (tempBool)
{
tempBool = !tempBool;
}
else
{
tempBool = true;
}
})">
<i class="fa @(tempBool ? "fa-compress" : "fa-expand")" aria-hidden="true"></i>
</button>
How can I combine them?我怎样才能将它们结合起来?
I tried it with the OnClientClick
Event, with JsRuntime.InvokeVoidAsync("expand(this.closest(.profile))");
我尝试了OnClientClick
事件,使用JsRuntime.InvokeVoidAsync("expand(this.closest(.profile))");
, or by putting both in the onclick event. ,或将两者都放入 onclick 事件中。
How can I execute a JavaScript function and C# in a button onclick event?如何在按钮 ZC0BB2196426022E8ADF9A5BEDD6 中执行 JavaScript function 和 C# 事件?
My JavaScript code I try to execute我尝试执行的 JavaScript 代码
EventPageExpandable.js: EventPageExpandable.js:
function expand(card) {
card.classList.toggle('profile--expanded');
// If card is not expanded after toggle, add 'unexpanded' class
if (!card.classList.contains('profile--expanded')) card.classList.toggle('profile--unexpanded');
// Else if card is expanded after toggle and still contains 'unexpanded' class, remove 'unexpanded'
else if (card.classList.contains('profile--expanded') && card.classList.contains('profile--unexpanded')) card.classList.toggle('profile--unexpanded');
}
How I tried to use JsRuntime:我如何尝试使用 JsRuntime:
await JsRuntime.InvokeVoidAsync("EventPageExpandable.expand", "this.closest('.profile')");
Or like this?还是像这样? But both doesn't work.但两者都不起作用。
await JsRuntime.InvokeVoidAsync("expand", "this.closest('.profile')");```
Inject the JSRuntime:注入 JSRuntime:
@inject IJSRuntime JsRuntime
Bind the onclick event of the button:绑定按钮的onclick事件:
<button @onclick=ButtonClicked>Test</button>
and execute the JavaScript function:并执行 JavaScript function:
private async Task ButtonClicked()
{
Console.WriteLine("From C#");
await JsRuntime.InvokeVoidAsync("console.log", "From js");
}
When invoking JS-functions, pass the function name as first argument followed by all parameters调用 JS 函数时,将 function 名称作为第一个参数传递,然后是所有参数
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.