javascript - 如果根据参数给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都被绑定最新赋值的参数。
问题解答
回答1: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) } 回答2:
// 给你写个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 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>
相关文章:
1. css - 移动端 line-height安卓错位,苹果机正常用,缩放解决了,可是又出来了占位的问题2. mysql begin work语句是干嘛的?3. javascript - 移动端css动画播放状态暂停在ios不起作用 animation-play-state4. node.js - 函数getByName()中如何使得co执行完后才return5. javascript - vue $set 整个数组6. docker-compose中volumes的问题7. 微信开放平台 - ios APP能不能打开微信然后通过微信跳转到指定的URL?8. 小程序怎么加外链,语句怎么写!求救新手,开文档没发现9. 新手 - Python 爬虫 问题 求助10. Mac环境下QT编译MySQL驱动屡次失败?如何?
