简体   繁体   中英

Javascript syntax for concatenating in URL

I can show orderB.id as table data. I want to use this value in the href, but I am struggling with syntax.

        var output = results.reduce(function (orderA, orderB){
            var row = "<tr>";
            row += "<td>" + orderB.name + "</td>";
            row += "<td>" + orderB.type + "</td>";
            row += "<td>" + orderB.id + "</td>";
            row += "<td><a href='/update/' + orderB.id + >Update</a></td>";
            return orderA + row;
        },"")

I have tried:

            row += "<td><a href='/update/' + orderB.id + >Update</a></td>";
            row += "<td><a href='/update/' + 'orderB.id' + >Update</a></td>";
            row += "<td><a href='/update/orderB.id' + >Update</a></td>";

These output:

  1. /update/
  2. /update/
  3. /update/orderB.id

I want for example: /update/3

use template literals :

row += `<td><a href="/update/${orderB.id}">Update</a></td>`;

or simply concat your variables with the htmml string like :

row += '<td><a href="/update/' + orderB.id + '">Update</a></td>';

As has been suggested, template literals are a good way to go, but you have to be careful about just sticking strings together to create HTML -- if there are characters like < , > , or & there can be problems. I'd use Lodash and modify the answer given by another poster like this:

row += `<td><a href="/update/${_.escape(orderB.id)}">Update</a></td>`;

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