简体   繁体   中英

Dynamically create an element with an event handler that takes a string

This is driving me insane.

I create a cell in a table dynamically through:

tr.append("<td>" + countryArr[i].ISO_id + "</td>");

I created a button that when clicked calls a function with the value countryArr[i].ISO_id . This value is a string and needs to be called in "quotes".

I cannot get the function to be called with quotes.

I've tried:

tr.append("<td><button type='button' onclick='showCyclists(" + cId  + ")'>Show country's cyclists</button></td>");
tr.append("<td><button type='button' onclick='showCyclists("" + cId  + "")'>Show country's cyclists</button></td>");
tr.append("<td><button type='button' onclick='showCyclists('" + cId  + "')'>Show country's cyclists</button></td>");

None of these work. Please help

使用ES6,您可以仅使用以下称为模板文字的内容 ,注意反引号`

tr.append(`<td><button type='button' onclick='showCyclists("${cId}")'>Show country's cyclists</button></td>`);

只需添加转义的引号showCyclists(\\"" + cId + "\\")

tr.append("<td><button type='button' onclick='showCyclists(\"" + cId  + "\")'>Show country's cyclists</button></td>");

You can't use single quotes because those are being used to delineate the attribute. You could use escaped double quotes to get this to work:

tr.append("<td><button type='button' onclick='showCyclists(\"" + 
          cId  + 
          "\")'>Show country's cyclists</button></td>");

However, while it is possible to get your approach to work by manipulating the strings, the solution you are trying to use here (inline event handlers, and furthermore, inline event handlers created from JavaScript strings) is a bad practice.

Save yourself some headaches and build up the elements properly. Your code might be a few lines longer, but it will be cleaner.

Good approach:

var button = $('<button type="button">')
               .text("Show country's cyclists")
               .on('click', function () { showCyclists(cId) });
var td = $('<td>').append(button);
tr.append(td);

Working example:

 function showCyclists(id) { console.log("Here are all the cyclists."); console.log(id); } var tr = $('tr'); var cId = '12345'; var button = $('<button type="button">') .text("Show country's cyclists") .on('click', function() { showCyclists(cId); }); var td = $('<td>').append(button); tr.append(td); 
 <script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script> <table> <tr></tr> </table> 

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