我有一个“下订单”按钮,其中包含一个单击事件,该事件将运行一些任务并通过 ajax 下订单。
我想添加另一个将在原始事件之前触发的点击事件,并执行一些操作和验证。
取决于结果:
这将是一个简单的示例,但我当然尝试了许多不同的方法,包括 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>
在您的场景中,因为触发
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);
});