Inline event handler(内联事件处理程序)
In the most simple way, you can use the confirm()
function in an inline onclick
handler.
(以最简单的方式,您可以在嵌入式onclick
处理程序中使用confirm()
函数。)
<a href="delete.php?id=22" onclick="return confirm('Are you sure?')">Link</a>
Advanced event handling(高级事件处理)
But normally you would like to separate your HTML and Javascript , so I suggest you don't use inline event handlers, but put a class on your link and add an event listener to it.
(但是通常您希望将HTML和Javascript分开 ,所以我建议您不要使用内联事件处理程序,而应在链接上放置一个类并为其添加事件侦听器。)
<a href="delete.php?id=22" class="confirmation">Link</a>
...
<script type="text/javascript">
var elems = document.getElementsByClassName('confirmation');
var confirmIt = function (e) {
if (!confirm('Are you sure?')) e.preventDefault();
};
for (var i = 0, l = elems.length; i < l; i++) {
elems[i].addEventListener('click', confirmIt, false);
}
</script>
This example will only work in modern browsers (for older IEs you can use attachEvent()
, returnValue
and provide an implementation for getElementsByClassName()
or use a library like jQuery that will help with cross-browser issues).
(该示例仅适用于现代浏览器(对于较旧的IE,您可以使用attachEvent()
, returnValue
并提供getElementsByClassName()
的实现,或者使用类似jQuery的库来解决跨浏览器问题)。)
You can read more about this advanced event handling method on MDN .(您可以在MDN上阅读有关此高级事件处理方法的更多信息。)
jQuery(jQuery的)
I'd like to stay far away from being considered a jQuery fanboy, but DOM manipulation and event handling are two areas where it helps the most with browser differences.
(我想远离被视为jQuery迷的地方,但是DOM操作和事件处理是两个在浏览器差异方面最有用的地方。)
Just for fun, here is how this would look with jQuery :(只是为了好玩,这就是jQuery的外观:)
<a href="delete.php?id=22" class="confirmation">Link</a>
...
<!-- Include jQuery - see http://jquery.com -->
<script type="text/javascript">
$('.confirmation').on('click', function () {
return confirm('Are you sure?');
});
</script>
与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…