jQuery: Set click from array loop

前端 未结 4 1239
爱一瞬间的悲伤
爱一瞬间的悲伤 2021-02-15 02:21

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..

相关标签:
4条回答
  • 2021-02-15 02:40

    Check the scope of your "Area" variable. You're basically assigning a global variable so on the last iteration "Area" is scoped outside of the loop.

    0 讨论(0)
  • 2021-02-15 02:46

    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]);
    }
    
    0 讨论(0)
  • 2021-02-15 02:48

    be sure that you added the click event handling after the DOM has been loaded you can include this on the head element:

    var Areas = ['ping','http', 'smtp', 'pop3'];
    
    $(document).ready(function() {
        $.each(Areas, function(i, v){
            var Area = '#show_fold_' + v;
            $(Area).click(function() {
                alert(Area);
            });
        });
    }
    
    0 讨论(0)
  • 2021-02-15 02:59

    It's a JavaScript thing; it's not jQuery related. What you're doing is creating a closure, but you're not understanding properly how they work.

    You might want to read up on http://blog.morrisjohns.com/javascript_closures_for_dummies, especially Examples 5, 6, and 7.

    0 讨论(0)
提交回复
热议问题