简体   繁体   中英

Call a javascript function from anchor tag inside td inside javascript code

Only Basic javascript knowledge is required.If anyone knows please help me. I don't know how to do it but i have tried it in many ways but still not able to pass the value.

Simply, i have a for loop and i have a td inside it. I want to call a javascript function from this td click but problem is i am unable to pass any parameter to this function.

the code is here :

 function GetContractList(abc) {
  var data = abc
  for (var it in data) {
            tab += "<tr>";
            tab += "<td>" + data[it].ContractCode + "</td>";
            if (data[it].ContractCode != "") {
                var Contract = data[it].ContractCode;
                 tab += "<td><a onclick='Delete_User(Contract);'>View</td>";
               // tab += "<td><a data=" + data[it].ContractCode + " href='javascript:Delete_User(this.data);'>View</td>";
            }
            else {
                tab += "<td></td>";
            }

As u can see, i have tried to pass parameter to Delete_User function but the syntax is somewhere broken.

  tab += "<td><a onclick='Delete_User(Contract);'>View</td>";

this line gives error-- Contract is not defined.

"<td><a data=" + data[it].ContractCode + " href='javascript:Delete_User(this.data);'>View</td>".

This line also doesnot passes any value to the function. Please someone help me out.

You need to escape the quote for the parameter of the function.

tab += '<td><a href="javascript:Delete_User(\'' + data[it].ContractCode + '\');">View</a></td>';
//                                          ^^                             ^^

 function Delete_User(id) { console.log('Delete_User', id); } var cc = '4711abc', tab = '<a href="javascript:Delete_User(\\'' + cc + '\\');">View</a>'; document.write(tab);

try:
var cont = data[it].ContractCode.replace(/"/g, '\\\\"');
tab += '<td><a onclick="Delete_User(\\''+cont+'\\');">View</td>";

first line encodes any double quotes
the second line inserts the contract as a parameter and adds single quotes around it

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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