爲了做到這一點,你需要將處理程序附加到頁面上的特定錨。對於像這樣的操作,使用標準框架如jQuery要容易得多。例如,如果我有以下HTML
HTML:
<a id="theLink">Click Me</a>
我可以使用下面的jQuery來裝一個事件的具體環節。
// Use ready to ensure document is loaded before running javascript
$(document).ready(function() {
// The '#theLink' portion is a selector which matches a DOM element
// with the id 'theLink' and .click registers a call back for the
// element being clicked on
$('#theLink').click(function (event) {
// This stops the link from actually being followed which is the
// default action
event.preventDefault();
var answer confirm("Please click OK to continue");
if (!answer) {
window.location="http://www.continue.com"
}
});
});
感謝,如果我點擊取消儘管它仍然打開鏈接/ – user1022585 2012-01-11 03:13:44
@ user1022585您需要返回false來停止鏈接導航。看到我的回答下面 - 確認'方法返回一個'布爾',你可以退出你的功能... – xandercoded 2012-01-11 03:18:38
對不起,我複製你的代碼,並且你的代碼是錯誤的。如果用戶說「好」,答案將設置爲「真」,因此我們不需要「!」,我改變了它。 – ocanal 2012-01-11 03:21:57