最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

Javascript for loop and alert - Stack Overflow

programmeradmin4浏览0评论

I am looping through a list of links. I can correctly get the title attribute, and want it displayed onclick. When the page is loaded and when I click on a link, all of the link titles are alerted one by one. What am I doing wrong?

function prepareShowElement () {
var nav = document.getElementById('nav');
var links = nav.getElementsByTagName('a');
for (var i = 0; i < links.length; i++) {
    links[i].onclick = alert(links[i].title);
    }
}

I am looping through a list of links. I can correctly get the title attribute, and want it displayed onclick. When the page is loaded and when I click on a link, all of the link titles are alerted one by one. What am I doing wrong?

function prepareShowElement () {
var nav = document.getElementById('nav');
var links = nav.getElementsByTagName('a');
for (var i = 0; i < links.length; i++) {
    links[i].onclick = alert(links[i].title);
    }
}
Share Improve this question edited Jul 18, 2011 at 6:49 Dan Grossman 52.4k10 gold badges114 silver badges101 bronze badges asked Jul 18, 2011 at 6:46 SquadronsSquadrons 2,5576 gold badges25 silver badges38 bronze badges 5
  • 3 This is your first language isn't it? You would do so much better to learn programming in another language. Javascript will teach you nothing that another language won't, but it's got the power to shoot you in the foot every time you pick it up. I know programming experts who do very wrong things in Javascript because they don't understand it. – jcolebrand Commented Jul 18, 2011 at 6:51
  • 1 @jcolebrand: Yeah, those other languages will do him much good when he need to show alerts in a website.... – Thilo Commented Jul 18, 2011 at 6:55
  • 1 This is indeed my first language. Fun stuff! – Squadrons Commented Jul 18, 2011 at 6:58
  • 1 I think it is a good idea to start learning programming with javascript. Professional programmers usually have lots of trouble with javascript, because they try to apply other highlevel technics found in languages like c++ to javascript, and pletely miss the point. – Ibu Commented Jul 18, 2011 at 7:00
  • @Ibu: I feel JS needs more "high level" things, but am not sure they are related to why the language can be tricky? @Squadrons: javascript used to be a good language to learn, relative to the other options. I might remend python now, but they have the same issues. There's one gotcha with both these languages: you have to declare new functions whenever you want to create snapshots of the stack (what programmers call "closures"). In javascript, I would actually remend using developer.mozilla/en/JavaScript/Reference/Global_Objects/… rather than for-loops. – ninjagecko Commented Jul 18, 2011 at 7:06
Add a ment  | 

5 Answers 5

Reset to default 7

What you were doing was actually running the alert function. enclosing the whole thing in an anonymous function will only run it when it is clicked

for (var i = 0; i < links.length; i++) {
    links[i].onclick = function () {
        alert(this.title);
       }
    }

You are assigning the onclick to the return value of alert(links[i].title); which doesn't make any sense, since onclick is supposed to be a function.

What you want instead is somethig like onclick = function(){ alert('Hi'); };

But

Since you are using a variable i in that loop you need to create a local copy of it onclick = function(){ alert(links[i].title); }; would just use the outer scope i and all your links would alert the same message.

To fix this you need to write a function that localizes i and returns a new function specific to each link's own onclick:

onclick = (function(i){ return function(e){ alert(links[i].title); }; })(i);

Final result:

function prepareShowElement () {
var nav = document.getElementById('nav');
var links = nav.getElementsByTagName('a');
for (var i = 0; i < links.length; i++) {
    links[i].onclick = (function(i){ return function(e){ alert(links[i].title); }; })(i);
    }
}    

You can use jquery. To display title of the link on click.

$("#nav a").click(function() {
    var title = $(this).attr('title');
    alert(title);
});
links.forEach(function(link) {
    link.onclick = function(event) {
        alert(link.title);
    };
}

Also note that your original solution suffered from this problem: JavaScript closure inside loops – simple practical example

By passing in our iteration variable into a closure, we get to keep it. If we wrote the above using a for-loop, it would look like this:

// machinery needed to get the same effect as above
for (var i = 0; i < links.length; i++) {
    (function(link){
        link.onclick = function(event) {
            alert(link.title);
        }
    })(links[i])
}

or

// machinery needed to get the same effect as above (version 2)
for (var i = 0; i < links.length; i++) {
    (function(i){
        links[i].onclick = function(event) {
            alert(links[i].title);
        }
    })(i)
}

You need change .onclick for a eventlistener same:

function prepareShowElement () {
  var nav = document.getElementById('nav');
  var links = nav.getElementsByTagName('a');
  for (var i = 0; i < links.length; i++) {
    links[i].addEventListener('click',function() { 
        alert(links[i].title);
    },false);
  }
}
发布评论

评论列表(0)

  1. 暂无评论