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. javascript - node.js服務端渲染解疑2. javascript - 求助關于js正則問題3. html5 - 如何解決bootstrap打開模態modal窗口引起頁面抖動?4. javascript - 求助這種功能有什么好點的插件?5. objective-c - ios百度地圖定位問題6. 微信開放平臺 - Android調用微信分享不顯示7. html - css 如何添加這種邊框?8. html5 - rudy編譯sass的時候有中文報錯9. javascript - 關于定時器 與 防止連續點擊 問題10. 為何 localStorage、sessionStorage 屬于html5的范疇,但是為何 IE8卻支持?
