我有一个按钮,它执行JS函数:

<button class="btn-orange btn" onclick="expand(this.closest('.profile'))">JavaScript</button>

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

我如何组合它们?

我try 了OnClientClick次,JsRuntime.InvokeVoidAsync("expand(this.closest(.profile))");次,或者把两者都放在onclick事件中.

如何在按钮点击事件中执行JavaScript函数和C?

我try 执行的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');
}

我是如何try 使用JsRuntime的:

await JsRuntime.InvokeVoidAsync("EventPageExpandable.expand", "this.closest('.profile')");

还是像这样?但两者都不起作用.

await JsRuntime.InvokeVoidAsync("expand", "this.closest('.profile')");```

推荐答案

注入JSRuntime:

@inject IJSRuntime JsRuntime

绑定按钮的onclick事件:

<button @onclick=ButtonClicked>Test</button>

并执行JavaScript函数:

private async Task ButtonClicked()
{
    Console.WriteLine("From C#");
    await JsRuntime.InvokeVoidAsync("console.log", "From js");
}

调用JS函数时,将函数名作为第一个参数传递,后跟所有参数

Javascript相关问答推荐

将数据从strapi提取到next.js,但响应延迟API URL

使用json文件字符串来enum显示类型字符串无法按照计算的enum成员值的要求分配给类型号

确定MutationRecord中removedNodes的索引

如何为GrapesJS模板编辑器创建自定义撤销/重复按钮?

如何使用侧边滚动按钮具体滚动每4个格?

JQuery. show()工作,但. hide()不工作

使用javascript将Plotly Expandable Sparkline转换为HighCharter Plot在bslib卡中

Promise Chain中的第二个useState不更新

如何让npx在windows中运行js脚本?

如何将Openjphjs与next.js一起使用?

如何使onPaste事件与可拖动的HTML元素一起工作?

如果Arrow函数返回函数,而不是为useEffect返回NULL,则会出现错误

使用ThreeJ渲染的形状具有抖动/模糊的边缘

在forEach循环中获取目标而不是父对象的属性

创建以键值对为有效负载的Redux Reducer时,基于键的类型检测

使用插件构建包含chart.js提供程序的Angular 库?

Reaction-SWR-无更新组件

处理TypeScrip Vue组件未初始化的react 对象

用内嵌的含selenium的Java脚本抓取网站

2.0.0-dev quill拖动文本不起作用如何使其拖动文本