JQuery click () function in for loop shows unexpected behavior

I would like to use the jQuery click () function in a for loop to make the three HTML elements interactive. I created a simple test case:

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">
<html xmlns="http://www.w3.org/1999/xhtml" xml:lang="en">
<head>
  <meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
  <script type="text/javascript" src="http://code.jquery.com/jquery-1.4.3.min.js" />
  <script type="text/javascript">
    $(window).load(function() {
      function loadContent(){
        var values = ['a','b','c'];
        for (var i = 0; i < values.length; ++i) {
          var id = values[i];
          alert(id);
          $('#' + id).click(function() {
            function2(id);
          });
        }
      }

      function function2(id) {
        // do some fancy stuff like...
        alert(id);
      }

      loadContent();
    });
  </script>
</head>
<body>
  <div id="map">
    <a id="a">a</a>
    <a id="b">b</a>
    <a id="c">c</a>
  </map>
</body>

As you can see, I would like to display the character “a” if I press “a” (a), show “b” by pressing “b” and so on. Unfortunately, the character 'c' is displayed when you click on 'a'. No other events are fired. I do not see the mistake I will make.

I am not worried if this code is effective or not. I just want to know why click () does not work as expected in this context. Thanks in advance for any tips or solution.

+3
5

:

  • id id="a", ( click). id="b", - id="c".
  • <script> , jQuery /> ></script>
  • </map> </div>
  • id , function2(this.id) .

/ .

0

"click" single "id". , . , .

-:

    for (var i = 0; i < values.length; ++i) {
      var id = values[i];
      alert(id);
      $('#' + id).click((function(id) {
        return function() { function2(id); };
      })());
    }

, for, , . Javascript "id" loadContent. "click" .

+2

3 . .

0

id 'a'. id a, b, c

0

<a></a> "" .

0
source

Source: https://habr.com/ru/post/1772530/


All Articles