如果根据参数给table中的tr绑定不同事件

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);

    }    

}

绑定相同函数,但是每个tr传的参数不同,应该怎样写呢。
现在这样写每个tr都被绑定最新赋值的参数。

DIEA
浏览 556回答 1
1回答

慕哥6287543

// 给你写个demo吧<!DOCTYPE html><html><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>&nbsp; &nbsp; function add (name) {&nbsp; &nbsp; &nbsp; &nbsp; alert(name);&nbsp; &nbsp; }&nbsp; &nbsp; function update() {&nbsp; &nbsp; &nbsp; &nbsp; var container = document.getElementById("ItemContainer");&nbsp; &nbsp; &nbsp; &nbsp; console.log(container);&nbsp; &nbsp; &nbsp; &nbsp; container.innerHTML = "";&nbsp; &nbsp; &nbsp; &nbsp; for(let i=0; i<5; i++) {&nbsp; &nbsp; &nbsp; &nbsp;&nbsp;&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; let name = i;&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; let tr = document.createElement('tr');&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp;&nbsp;&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; let td = document.createElement('td');&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; td.innerHTML = i;&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; tr.appendChild(td);&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; console.log(name)&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; tr.onclick = function (){&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; return add(name);&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; };&nbsp;&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; container.appendChild(tr);&nbsp; &nbsp; &nbsp; &nbsp; }&nbsp;&nbsp;&nbsp; &nbsp; }&nbsp; &nbsp; update()&nbsp;&nbsp;</script></body></html>
打开App,查看更多内容
随时随地看视频慕课网APP

相关分类

JavaScript