使用PrototypeJs或纯JS,如何避免点击事件但稍后触发原始处理程序?

问题描述 投票:0回答:1

我有一个“下订单”按钮,其中包含一个单击事件,该事件将运行一些任务并通过 ajax 下订单。

我想添加另一个将在原始事件之前触发的点击事件,并执行一些操作和验证。

取决于结果:

    我想阻止其他事件被触发
  1. 或者如果成功,则继续并调用其他点击侦听器。
然而,我正在努力使用 PrototypeJS 或纯 JavaScript 来实现这一目标。

这将是一个简单的示例,但我当然尝试了许多不同的方法,包括 overrigind Event.observe 方法、克隆按钮等等。

任何想法表示赞赏。

var button = $('onestepcheckout-place-order-button') //Original event button.observe('click', function(e) { console.log('Order submitted') }) // New event (I only have access to modify from here onwards) button.observe('click', function(event) { if (confirm('Are you sure?') === false) { console.log('The order should not be submitted') event.preventDefault() event.stopPropagation() return false } // The other events should be triggered (order submitted) button.fire('click') });
<script src="https://cdnjs.cloudflare.com/ajax/libs/prototype/1.7.3/prototype.js"></script>
<button id="onestepcheckout-place-order-button" type="button"><span>Place order</span></button>

javascript prototypejs
1个回答
0
投票
我认为您遇到了浏览器设置的保护措施,该保护措施可以防止 JS 人为触发不属于原始点击事件的点击事件。例如,如果您通过鼠标移动事件触发事件,浏览器将阻止您触发元素上的单击事件。

在您的场景中,因为触发

confirm()

 方法会中断单击事件从一个处理程序到下一个处理程序的“流”。

这是我的建议,将订单提交处理程序提取到单独的方法定义中,以便在将事件传递给该方法时调用该方法。原始的单击事件侦听器可以调用该方法,以及具有“您确定吗”

confirm()

 调用的新方法。

function submitorder(event){ //... original submit order } $('onestepcheckout-place-order-button').observe('click',submitorder); // OR $('onestepcheckout-place-order-button').observe('click',function(event){ if (confirm('Are you sure?') === false) { console.log('The order should not be submitted') event.preventDefault() event.stopPropagation() return false } submitorder(event); });
    
© www.soinside.com 2019 - 2024. All rights reserved.