search

Home  >  Q&A  >  body text

javascript - How to bind different events to tr in table based on parameters

function update() {
    var container = document.getElementById("ItemContainer");
    container.innerHTML = "";
    for(var i=0;i<this.bookMarkList.length;i++){        
        var name = this.ItemContainer[i].name;
        var tr = document.createElement('tr');              
        var td = document.createElement('td');
        tr.appendChild(td);
        tr.onclick =  function(){add(name);}; 
      container.appendChild(tr);
    }    
}

The same function is bound, but the parameters passed by each tr are different. How should it be written?
Now write like this, each tr is bound to the latest assigned parameter.

PHPzPHPz2793 days ago681

reply all(2)I'll reply

  • 过去多啦不再A梦

    过去多啦不再A梦2017-05-16 13:24:03

        for(var i=0;i<this.bookMarkList.length;i++){        
            (function(i){
                var name = this.ItemContainer[i].name;
                var tr = document.createElement('tr');              
                var td = document.createElement('td');
                tr.appendChild(td);
                tr.onclick =  function(){add(name);}; 
                container.appendChild(tr);
            })(i)
        }  

    reply
    0
  • 天蓬老师

    天蓬老师2017-05-16 13:24:03

    // 给你写个demo吧
    <!DOCTYPE html>
    <html lang="en">
    <head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <meta http-equiv="X-UA-Compatible" content="ie=edge">
    <title>Document</title>
    </head>
    <style>
    
    </style>
    <body>
    <table id="ItemContainer" border="1" width="100"></table>
    <script>
        function add (name) {
            alert(name);
        }
        function update() {
            var container = document.getElementById("ItemContainer");
            console.log(container);
            container.innerHTML = "";
            for(let i=0; i<5; i++) {        
                let name = i;
                let tr = document.createElement('tr');              
                let td = document.createElement('td');
                td.innerHTML = i;
                tr.appendChild(td);
                console.log(name)
                tr.onclick = function (){
                    return add(name);
                }; 
              container.appendChild(tr);
            }  
        }
        update()  
    </script>
    </body>
    </html>
    

    reply
    0
  • Cancelreply