jQuery: Set click from array loop

前端 未结 2 867
耶瑟儿~
耶瑟儿~ 2021-02-15 01:57

I have a series of divs in a pattern of header/body, where a click on the header will show the body in question.

This all happens with .click initialized on page ready..

2条回答
  •  失恋的感觉
    2021-02-15 02:54

    Yes, I have run into this problem all too often. Area is a global variable since it does not have var before it. Also, don't use a for...in construct.

    But you might still run into a similar problem. God knows how many scripts I've debugged because of a similar bug. Doing the following guarantees proper scoping:

    var Areas = ['ping','http', 'smtp', 'pop3'];
    
    for( var i = 0; i < Areas.length; i++ ){
      (function(area) {
        $(area).click(function(){ alert(area); /* ShowArea(area); */ });
      })(Areas[i]);
    }
    

提交回复
热议问题