如何将当前JavaScript事件重新附加到其他元素



我正试图截获一个JavaScript事件和preventDefault,以显示警告模式。如果用户选择接受警告,则单击"继续"并继续执行他们正在执行的操作。不过,可能会发生多个事件,所以我认为处理它的最佳方法是将当前事件附加到"继续"按钮。

这是我迄今为止的代码:

$(document).on('click', 'nav.pagination a', function(e) {
e.preventDefault;
var checkedBoxes = $('.checkbox-pagination-warning:checked');
if(checkedBoxes.length > 0) {
$('.checked-box-warning-modal').modal("open");
// This is where I would attach the event to this button:
//
// $('.checked-box-warning-modal a.continue')
} else {
$(this).unbind("click");
}
})

对于上下文,我警告用户,在他们导航或分页离开之前,页面上有复选框。

此外,分页由Stimulus处理。

这是HTML:的一个例子

<nav class="pagination">
<a href="/entities/1?signatories_page=1" class="pagination-first-page" data-action="click->entities--add-existing-signatories#onPaginate">
1
</a>
<span class="pagination-current-page">
2
</span>
</nav>

那么,我如何将运行preventDefault的事件附加到"继续"按钮,以便事件像什么都没发生一样继续?

我注意到您在此处定义数据操作时出错:

<a href="/entities/1?signatories_page=1" class="pagination-first-page"click->entities--add-existing-signatories#onPaginate">
1

[更新]因此,我认为您可以使用event.prventDefault((来阻止分页链接操作。然后,您将触发一个全局事件,该事件将在顶级控制器中捕获。您可以将当前的分页链接(event.target(传递给将在新控制器中捕获的这个新事件。

类似于:

<!-- this controller will handle showing the modal when asked -->
<div data-controller="main" data-action="recheck@document->main#checkWithModal">
<!-- this is the controller that captures the click on pagination links -->
<div data-controller="pagination"></div>
</div>

----- javascript
You would use this to dispatch the event
document.dispatchEvent(new Event('recheck', {bubbles: true, detail: { existing event target here }}))

最新更新