Loading ...
Sorry, an error occurred while loading the content.

190Re: [jslint] Re: Be careful when making functions in a loop...

Expand Messages
  • William Chapman
    Aug 20, 2008
      Ben,

      Another approach:

      function main() {
      var arr = ['a', 'b', 'c'];
      var closedValue;
      for (var i = 0; i < 3; i++) {
      closedValue = i;
      document.getElementById(arr[i]).onclick = function(closedValue) {
      alert(closedValue);
      });
      }
      }

      In your code, this line:
      alert(i)
      displays the value of i **when the button is clicked**, as opposed to,
      **when the function is assigned to onclick.**

      For me, the original point - that one needs to take care when defining
      functions in a loop - is valid. Which isn't the same as saying it's never a
      good idea.

      -- Bill

      On Tue, Aug 19, 2008 at 1:40 PM, Ben Collver <tylx@...> wrote:

      > I created a page with three buttons, a, b, and c. When you click on a
      > button, it alerts its number. I modified the loop to attach an onclick
      > handler to each input element and alert the index. They all alert 4 as
      > expected.
      >
      > I must have misunderstood the instructions. The page is at
      > http://bencollver.googlepages.com/looptest.html
      >
      > Ben
      >
      > __________________________________________________________
      > Posted by: "Douglas Crockford" douglas@...<douglas%40crockford.com>douglascrockford
      > Date: Wed Aug 13, 2008 11:31 am ((PDT))
      >
      >
      > Create a page with three buttons, a, b, and c. When you click on a
      > button, it alerts its number. Modify your loop to get each element by
      > id and attach an onclick handler that alerts the index. If you do it
      > incorrectly, they will all alert the same wrong number.
      >
      >
      >


      [Non-text portions of this message have been removed]
    • Show all 8 messages in this topic