如何防止 Blazor 服务器端的事件冒泡?
在我的 blazor 服务器端应用程序中,我有代表数据集的卡片,用户可以管理这些数据集。 它们看起来像这样:
相关代码如下所示:
<div class="card h-100 text-dark" @onclick="() => OnDatasetSelected(dataset)">
<!-- header image -->
<div class="card-body position-relative">
<div class="dropdown dropstart">
<button type="button" data-bs-toggle="dropdown" aria-expanded="false">
<i class="bi bi-three-dots-vertical"></i>
</button>
<ul class="dropdown-menu">
<!-- menu content -->
</div>
<!-- card content -->
</div>
从代码中可以看出,我当前正在使用 引导下拉列表(在我的例子中为 dropleft)组件。 这工作得很好 - 或者更确切地说,如果不是卡上的 @onclick
事件,它会调用代码来选择数据集并导航到另一个页面。
问题基本上是:如果单击其中的元素,如何防止 OnClick
事件。我想,我要问的是:如何防止 HTML 中的事件冒泡?是否可以不向内部下拉元素添加代码(bootstrap-dropdowns 的显示是通过 popper.js 完成的,它是外部的)
In my blazor server side application I have cards representing datasets, which the user can manage.
They look like this:
The relevant code looks like this:
<div class="card h-100 text-dark" @onclick="() => OnDatasetSelected(dataset)">
<!-- header image -->
<div class="card-body position-relative">
<div class="dropdown dropstart">
<button type="button" data-bs-toggle="dropdown" aria-expanded="false">
<i class="bi bi-three-dots-vertical"></i>
</button>
<ul class="dropdown-menu">
<!-- menu content -->
</div>
<!-- card content -->
</div>
As one can see from the code, I'm currently adding the context menu (three vertical dots) using the template code from bootstraps dropdown (dropleft in my case) component.
This works fine - or rather it would if it weren't for the @onclick
event on the card, which calls the code to select the dataset and navigate to another page.
Question basically is: How can I prevent the OnClick
event, if an element inside is being clicked on. I guess, what I'm asking is: How can I prevent event bubbling in HTML? Is it possible without adding code to the inner dropdown element (display of bootstrap-dropdowns is done with popper.js, which is external)
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
哈哈,在发布后 5 分钟此处找到了答案:
只需使用 < code>onclick="event.stopPropagation();" 以防止事件冒泡。
所以最后我只需将其添加到下拉容器中:
现在我可以单击菜单按钮:
重要编辑:
如果您遇到
onclick="event.stopPropagation();"
阻止触发内部按钮的@onclick
事件的问题,可以直接使用以下命令内部按钮:单击按钮时将调用 MyFunction,但会阻止事件传播到父元素。
Lol, found the answer here 5 minutes after posting:
Simply use
onclick="event.stopPropagation();"
to prevent the event bubbling.So in the end I just add this to the dropdown container:
And now I can click my menu button:
Important Edit:
In case you have issues with
onclick="event.stopPropagation();"
preventing the@onclick
event of the inner button to be fired, one can use the following directly at the inner button:This will call
MyFunction
when clicking the button, but prevents the event to be propagated to the parent elements.