如果你想這樣做沒有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>
'body'在''
標籤?什麼時候?點擊「a:第n個孩子(4)」? – Harry是的,這兩個 –