开发者

HTML and JavaScript "this"

开发者 https://www.devze.com 2023-03-27 01:52 出处:网络
I have this HTML code right here.. <ul> <li><a href=\"#\" id=\"0\">Services</a></li>

I have this HTML code right here..

<ul>
    <li><a href="#" id="0">Services</a></li>
    <li><a href="#" id="1">Portfolio</a></li>
  开发者_如何学运维  <li><a href="#" id="2">Contact</a></li>
</ul>

And I have this JavaScript over here when you click on one of the links:

alert(this.id);

Question: is it possible to determine which "A" tag was clicked, without setting extra "id" attribute for links? With JavaScript it would be like this:

document.getElementsByTagName("a")[number];

And I need that number from "this".

I hope you understand what I meant. Sorry for my english.


Sure:

var index = this.parentNode.parentNode.childNodes.indexOf(this.parentNode);

NodeList.prototype.indexOf = function(obj) {
    for (var i = 0; i < this.length; i++) {
        if (this[i] == obj) return i;
    }
    return undefined;
}


Here is less elegant, but working, solution:

window.onload = function() {
    var links = document.getElementsByTagName("a");
    for (var i = 0; i < links.length; i++) {
        links[i].onclick = function() {
            var index = FindIndex(this);
            alert("index: " + index);
            return false;
        };
    }
};

function FindIndex(oLink) {
    var listItem = oLink.parentNode;
    var oList = listItem.parentNode;
    var allItems = oList.getElementsByTagName("li");
    for (var i = 0; i < allItems.length; i++) {
        if (allItems[i] === listItem)
            return i;
    }
    return -1;
}

Live test case.


Or:

<a href="#" onclick='doSomething(this)'>

Edit

After re-reading your question, it appears you want something along the lines of @Tim van Elsloo, but I'll leave this up for information purposes anyway.

Edit 2

After re-re-reading your question, are you just looking for GET?

<a href='?clicked=1'>Click Me</a>
0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号