代码之家  ›  专栏  ›  技术社区  ›  Quintus

在动态JQuery元素上设置动态数据

  •  2
  • Quintus  · 技术社区  · 16 年前

    我是JQuery的新手,对Javascript也没有太多的背景知识,所以这可能会导致我的问题。。。我尝试动态生成一个项目列表,并将click事件绑定到每个动态生成的元素。我可以创建列表并成功绑定click事件,但是我遇到了一个绊脚石。

    我的计数器变量的值(2)。

    可以

    我的测试页:

    <!DOCTYPE html>
    <html>
      <head>
        <title>Test</title>
    
        <script type="text/javascript" src="http://www.google.com/jsapi"></script>
        <script type="text/javascript">google.load("jquery", "1.3.2");</script>
    
        <script type="text/javascript">
    function generateList() {
      var listElement = $('#unsortedList');
      var dataArr = new Array();
      dataArr["name1"] = "value1";
      dataArr["name2"] = "value2";
    
      // Clear any existing HTML
      listElement.html('');
    
      var i = 0;
      for(item in dataArr) {
        listElement.append('<li><div id="item' + i + '">Item ' + i + '</div></li>');
    
        $('#item' + i).click(function() {
          alert(i);
          $('#item' + i).html("You clicked item " + i);
        });
    
        i++;
      }
    }
    
    $(document).ready(function(e){
      generateList();
    });
    
        </script>
      </head>
      <body>
        <h1>Test List</h1>
        <ul id="unsortedList">
        </ul>
      </body>
    </html>
    

    2 回复  |  直到 16 年前
        1
  •  5
  •   NM.    16 年前

    这样做有效:

     $('#item' + i).click((function(x) {
              return function(){
                  $('#item' + x).html("You clicked item " + x);
              };
            })(i));
    

    http://jsfiddle.net/uLGxb/

        2
  •  0
  •   Tim Cooper    14 年前

          return function(){
              $(this).html("You clicked item " + x);
          };