如果您的 DOM 对象是在页面加载后的某个时间动态创建的,那么您将需要使用委托事件处理以便从中获取事件,即使您的事件处理程序安装在相关对象之前也是如此。您可以使用 jQuery 1.7+ 的动态形式来做到这一点.on()
:
jQuery(document).on('click', '#_Offer_Something', function(){
if( !confirm('Delete?') ) { //show confirm dialog
return false; //do nothing if cancel is clicked (prevent the browser from following clicked link)
}else{
window.location.replace("http://stackoverflow.com");
}
});
从技术上讲,它的工作方式是所有点击事件都在祖先链上冒泡(除非沿途的某些对象停止冒泡过程)。在这种情况下,我们在对象上安装了一个点击处理程序document
,它会监视源自与选择器匹配的对象的点击事件#_Offer_Something
。
For best performance, you wouldn't actually bind this event handler to the document
object. Instead, you would pick a static parent object (some parent of #_Offer_Something
) that does exist at the time you install the event handler. I picked the document
object here only because you didn't disclose the rest of your HTML so I don't know what a better choice would be.