您可以将click
处理程序附加到单个链接:
var links = document.getElementsByTagName('a');
var index;
for (index = 0; index < links.length; ++index) {
links.onclick = linkClickHandler;
}
function linkClickHandler() {
var x = this.href.indexOf('?');
var query = x >= 0 ? this.href.substring(x + 1) : null;
if (query) {
// Do the ajax thing...
// (your code here)
// ...and prevent the link from being followed
return false;
}
}
...或者(这可能更好)对document
自己:
document.onclick = function(e) {
var target, x, query;
e = e || window.event;
target = e.target;
if (target.tagName.toUpperCase() === "A") {
x = target.indexOf('?');
query = x >= 0 ? target.substring(x + 1) : null;
if (query) {
// Do the ajax thing...
// (your code here)
// ...and prevent the link from being followed
return false;
}
}
};
在任何一种情况下,在现代浏览器上,您可能希望使用addEventListener
而不是onclick
,并调用preventDefault
事件对象。但是 IE8 仍然使用attachEvent
而不是addEventListener
.
(return false;
来自老式的 DOM0 事件处理程序,例如onclick
阻止事件的默认操作;详细信息。)