简体   繁体   中英

Put single quotes in string javascript

Currenly i use javascript to bind a table dynamically..

I need single quotes to delimit a string..

Code :-

var str ="";
str += "<td><a onclick='showFlightsByName("+val.Name+")' href='javascript:;'><span>" + val.Name + "</span></a></td>";

Current Ouput :-

<a onclick="showFlightsByName(AirTran Airways)" href="javascript:;"><span>Airways Airways</span></a>

Desire Output :-

<a onclick="showFlightsByName('AirTran Airways')" href="javascript:;"><span>Airways Airways</span></a>
"<td><a onclick='showFlightsByName("+val.Name+")' href='javascript:;'><span>" + val.Name + "</span></a></td>"

应该

"<td><a onclick=\"showFlightsByName('"+val.Name+"')\" href=\"javascript:;\"><span>" + val.Name + "</span></a></td>"

Try this:

var str ="";
str += "<td><a onclick=\"showFlightsByName('"+val.Name+"')\" href=\"javascript:;\"><span>" + val.Name + "</span></a></td>";

Often when working with HTML it's easier to use ' instead of " for Strings, like this:

var str = '<td><a onclick="showFlightsByName("' + val.Name + '")" href="javascript:;"><span>' + val.Name + '</span></a></td>';

However, have you considered using JS to build the DOM object?

var a = document.createElement("a");
a.href = "javascript:;";
a.onclick = "showFlightsByName(" + val.Name + ")";
a.appendChild(document.createElement("span").innerHTML(val.name));
var td = document.createElement("td");
td.appendChild(a);

That might not be 100%. It's been a while since I've coded in plain JS. JQuery makes it too easy.

edit: on that note...

var $a = $('<a>').append($('<span>').text(val.Name)).click(function() {
    showFlightsByName(val.Name); 
});
$('<td>').append($a).appendTo("WHEREVER");

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