I'm trying to pass arguments to onclick handler. The table rows are constructed dynamically in a loop and each row contains a tag with different args. Suppose there are two rows, and when clicking the first img, the argument is always the argument corresponding to the second(last) row.
JS code
for(...){
id = get_id(); // every row's id is different
img = '<img src="/img/icon-view.png" height="20" width="20" style="cursor:pointer"
onclick="view_detail(id)">'
row = ('<tr> ' + '<td>' + img + '</td>' + '</tr>')
$("#table_1").append(row)
}
function view_detail(id){
...
// the first row's id is always the second id's row
}
Comment: Jquery passing ID from <img> to function gives a solution, but the trick here is id is a variable.
<img onclick="Myfunction(this.id)" src="files/pic/Website.png" id="Website">
Finally I found a workaround which is very simple - create img element and converts to string, and then put the string in row tag.
Sample code:
var img = document.createElement("img")
img.setAttribute("id","local_variable")
img.setAttribute("onclick","view_detail(this.id)")
var img_str = img.outerHTML(img)
row = '<tr>' + '<td>' + img_str + '</td>' + '</tr>'