javascript - Blazor在一键onclick事件中执行C#和JS函数

标签 javascript c# html blazor

我有一个按钮,它执行一个 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/

相关文章:

jquery - 菜单中 FadeItems 的结构和设计

javascript - 如果选中,如何禁用/启用带有复选框的按钮

javascript - 如何在javascript中计算数组内的数组元素?

c# - 如何使函数执行超时

javascript - 无法读取未定义的属性 'name'。购物车

javascript - 如何在没有javascript的情况下以jsp形式验证客户端的日期?

javascript - 如何让 React 更新组件并在组件更新时运行函数?

javascript - 将 'a' 作为此箭头函数的输入是错误吗?

c# - 如何从我创建的消息框中返回是或否?

c# - 绑定(bind)到模型对象列表的 ViewModels 的 WPF 列表