jQuery click on Appended Element not working

后端 未结 5 981

I have an array. I am getting data from Array and using it in jQuery Append to list. But when I am clicking on list item its only showing the last element.

var a         


        
5条回答
  •  误落风尘
    2021-01-29 05:17

    Move the event handler outside the for loop and persist the arbitrary data with element using .data(key, value) which can later be retried using .data(key) in the current element context.

    Additionally, You have syntax error while retrieving array elements

    var array = [
      [1, 2, 7],
      [3, 4, 8],
      [5, 6, 9]
    ];
    for (var i = 0; i < array.length; i++) {
      //Rectify syntax errors while reading 
      var firstVal = array[i][0];
      var secondVal = array[i][1];
      var thirdVal = array[i][2];
    
      var list = "

    " + firstVal + "

    " + "

    " + secondVal + "

    "; $(list).data('item', thirdVal).appendTo("#myDiv"); } $(".divClass").on('click', function() { console.log($(this).data('item')); })
    .divClass {
      border: 1px solid black
    }
    
    


    Or, use let instead of var and bind element handler to element then append it to list. A good read What's the difference between using "let" and "var" to declare a variable?

    var array = [
      [1, 2, 7],
      [3, 4, 8],
      [5, 6, 9]
    ];
    for (var i = 0; i < array.length; i++) {
      //Rectify syntax errors while reading 
      var firstVal = array[i][0];
      var secondVal = array[i][1];
      let thirdVal = array[i][2];
    
      var list = "

    " + firstVal + "

    " + "

    " + secondVal + "

    "; $(list).on('click', function() { console.log(thirdVal); }).appendTo("#myDiv"); }
    .divClass {
      border: 1px solid black
    }
    
    

提交回复
热议问题