如果你想在没有 jQuery 的情况下这样做:
<script>
window.onload = function() {
var anchors = document.getElementsByTagName('a');
for(var i = 0; i < anchors.length; i++) {
var anchor = anchors[i];
anchor.onclick = function() {
alert('ho ho ho');
}
}
}
</script>
并且在没有 jQuery 的情况下做到这一点,并且只在一个特定的类上(例如:hohoho):
<script>
window.onload = function() {
var anchors = document.getElementsByTagName('a');
for(var i = 0; i < anchors.length; i++) {
var anchor = anchors[i];
if(/\bhohoho\b/).match(anchor.className)) {
anchor.onclick = function() {
alert('ho ho ho');
}
}
}
}
</script>
If you are okay with using jQuery, then you can do this for all anchors:
<script>
$(document).ready(function() {
$('a').click(function() {
alert('ho ho ho');
});
});
</script>
而这个 jQuery 片段仅将其应用于具有特定类的锚点:
<script>
$(document).ready(function() {
$('a.hohoho').click(function() {
alert('ho ho ho');
});
});
</script>