简体   繁体   English

JavaScript-For循环按钮onclick

[英]JavaScript - For loop button onclick

I've a javascript that goes through for loop, make table in HTML page and then calls specific function to update specific values for that user. 我有一个JavaScript,它会进行for循环,在HTML页面中创建表,然后调用特定函数来为该用户更新特定值。

function getUsers() {
  //get all users as "parsedJSON" array
  for (var i=0; i<countrows; i++ ) {
    row.insertCell(0).innerHTML = parsedJSON[i].samaccountname;
    row.insertCell(1).innerHTML = parsedJSON[i].givenname;
    row.insertCell(2).innerHTML = parsedJSON[i].surname;
    var userName = parsedJSON[i].samaccountname;
    row.insertCell(3).innerHTML = "<button id='userName' onclick = 'updateUser(this.id)'> ActionUser</button>";
  }
}

function updateUser(userName) {
    //Function with about 30 lines to update user
}

Now, my question is: How can I know, which specific user's button was clicked and how can I pass its username to updateUser function? 现在,我的问题是:我怎么知道,单击了哪个特定用户的按钮,以及如何将其用户名传递给updateUser函数?

Thanks in Advance 提前致谢

Here 这里

var userName = parsedJSON[i].samaccountname;
row.insertCell(3).innerHTML = "<button id='userName' onclick = 'updateUser(this.id)'> ActionUser</button>";

You are actually assigning the string "userName" into the button instead of passing the value of userName , so your code should be 您实际上是在按钮中分配字符串“ userName”,而不是传递userName的值,因此您的代码应为

row.insertCell(3).innerHTML = "<button id='" + userName + "' onclick = 'updateUser(this.id)'> ActionUser</button>";

For identifying the clicked button, since you are passing the button's id to the updateUser function, you can use document.getElementById to get the clicked element. 为了标识单击的按钮,由于将按钮的id传递给updateUser函数,因此可以使用document.getElementById来获取单击的元素。

function updateUser(userName) {
    var clickedButton = document.getElementById('username');

    // This will work if this function is guaranteed to only be used by HTML element
    var thisButton = this;
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM