Detect which link was clicked? Always returns undefined. What's wrong?
I am trying to detect which of the first 3 links is being clicked on by outputting the links ID.
It always returns undefined
.
What's wrong?
<html>
<head>
<script src="http://code.jquery.com/jquery-latest.js"></script>
<script type="text/javascript">
window.onload = function() {
onclick = function() {
alert(this.id);
return false;
}
}
</script>
</head>
<body>
<a class="a" name="a" id="1" href="#">---1---</a>
<a class="a" name="a" id="2" href="#">---2---</a&开发者_高级运维gt;
<a class="a" name="a" id="3" href="#">---3---</a>
<a href="#"> normal link </a>
</body>
</html>
You are not targeting any of the links.
window.onload = function() {
$("a.a").click(function() {
alert(this.id);
return false;
});
}
What this is doing ($("a.a").click(function(){
) is looking for any click events on anchors of class name 'a' and run the following anonymous function.
You haven't used even a single bit of Jquery. Check here for the jquery version that i made on jsfiddle: http://jsfiddle.net/8tu8W/
Modified your HTML a bit
<a class="a" name="a" id="anch1" href="#">---1---</a>
<a class="a" name="a" id="anch2" href="#">---2---</a>
<a class="a" name="a" id="anch3" href="#">---3---</a>
<a href="#"> normal link </a>
Changed your anchor ids and introduced document ready event.
$(function(){
$("a.a").click(function(){
alert (this.id);
});
});
Something like this. You will add clickable links to array, then bind click event to document, in event method you will get target of click a find if it is and on which position in array.
window.onload = function() {
var clickableLinks = [];
var links = document.getElementsByTagName("a");
for(var i=0,len=links.length;i< len;i++) {
var link = links[i];
if(link.className.split(" ").indexOf("a") != -1) { // Or another detection
clickableLinks[clickableLinks.length] = link;
}
}
document.attachEvent('onclick', clicked); // IE
document.addEventListener('click', clicked, false); // Other browsers
function clicked(event) {
var target;
if (event.target) {target = event.target};
if (event.srcElement) {target = event.srcElement};
var index = clickableLinks.indexOf(target);
if(index != -1) {
alert("clicked at", index+1, "link");
}
}
精彩评论