我有一个按钮,它执行一个 JS 函数:
<button class="btn-orange btn" onclick="expand(this.closest('.profile'))">JavaScript</button>
还有一个按钮,它执行 C# 并根据 bool 值切换图标:
<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>
如何组合它们?
我尝试使用 OnClientClick
事件,使用 JsRuntime.InvokeVoidAsync("expand(this.closest(.profile))");
,或者将两者都放入onclick 事件。
如何在按钮的点击事件中执行 JavaScript 函数和 C#?
我尝试执行的 JavaScript 代码
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');
}
我是如何尝试使用 JsRuntime 的:
await JsRuntime.InvokeVoidAsync("EventPageExpandable.expand", "this.closest('.profile')");
还是这样?但两者都不起作用。
await JsRuntime.InvokeVoidAsync("expand", "this.closest('.profile')");```
最佳答案
注入(inject) JSRuntime:
@inject IJSRuntime JsRuntime
绑定(bind)按钮的onclick事件:
<button @onclick=ButtonClicked>Test</button>
并执行 JavaScript 函数:
private async Task ButtonClicked()
{
Console.WriteLine("From C#");
await JsRuntime.InvokeVoidAsync("console.log", "From js");
}
调用 JS 函数时,将函数名称作为第一个参数传递,然后是所有参数
关于javascript - Blazor在一键onclick事件中执行C#和JS函数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/73107037/