English 中文(简体)
循环的 javascription 只给出元素数
原标题:javascript for loop only give the number of elements

I have a list of 3 links, that I wanna iterate through, so each one of them can do something. But when I use the for-loop, it only gives me 3 in the console, which is the number of links in the list. I wanna the console to show each of them like so: 0, 1, 2;

另外,我如何获得每个链接的索引位置?

见以下代码:http://jsfiddle.net/c8Wdj/

请不要 JQuery 或任何库...

JavaScript:

(function(){
    var triggers = document.getElementById( some-list ).getElementsByTagName( a );

    for (var i = 0, max = triggers.length; i < max; i += 1) {
        triggers[i].addEventListener( mouseenter , function(e) {

            console.log(i);

        }, false);
    }

}());

HTML:

<ul id="some-list">
    <li><a href="#">One</a></li>
    <li><a href="#">Two</a></li>
    <li><a href="#">Three</a></li>
</ul>调

最佳回答

因为没有范围, 所以当您控制台. log( i) 时, 它会使用 i 的最新值 。 请试这个 :

for (var i = 0, max = triggers.length; i < max; i += 1) {
    (function(num){
        triggers[i].addEventListener( mouseenter , function(e) {
            console.log(num);
        }, false);
    })(i);
}
问题回答

一个共同的做法是在循环的每次迭代中创建新的变量范围,方法是援引函数,将 > i 传入其中,并返回一个引用该值的函数。

但如果你只需要引用一些轻量级数据,比如数字, 另一种方法就是简单地在元素上加一个扩展属性。

for (var i = 0, max = triggers.length; i < max; i += 1) {
    triggers[i].__i__ = i;
    triggers[i].addEventListener( mouseenter , function(e) {
        console.log(this.__i__);
    }, false);
}

这不要求嵌套变量范围的间接费用。

DEMO: http://jsfiddle.net/c8Wdj/5/

可能与 IE6 (我不记得) (我不记得) 存在问题,但这应该无关紧要,因为希望你不再支持其JS环境。 :





相关问题
selected text in iframe

How to get a selected text inside a iframe. I my page i m having a iframe which is editable true. So how can i get the selected text in that iframe.

How to fire event handlers on the link using javascript

I would like to click a link in my page using javascript. I would like to Fire event handlers on the link without navigating. How can this be done? This has to work both in firefox and Internet ...

How to Add script codes before the </body> tag ASP.NET

Heres the problem, In Masterpage, the google analytics code were pasted before the end of body tag. In ASPX page, I need to generate a script (google addItem tracker) using codebehind ClientScript ...

Clipboard access using Javascript - sans Flash?

Is there a reliable way to access the client machine s clipboard using Javascript? I continue to run into permissions issues when attempting to do this. How does Google Docs do this? Do they use ...

javascript debugging question

I have a large javascript which I didn t write but I need to use it and I m slowely going trough it trying to figure out what does it do and how, I m using alert to print out what it does but now I ...

Parsing date like twitter

I ve made a little forum and I want parse the date on newest posts like twitter, you know "posted 40 minutes ago ","posted 1 hour ago"... What s the best way ? Thanx.

热门标签