简体   繁体   中英

Passing an array to a function and escaping double quotes in Javascript

I am generating dynamic HTML and want to pass an array to the calling function. The array is also being dynamically generated.

The contents of pinfoarray are somewhat like this "Ice Hockey","Junior Basketball","Ladies Soccer"

var theHost = "<a href='#someDialog' onclick='chnghost(' + pinfoarray + ');' data-toggle='modal' class='button'>Change</a>";

How can make it send the array to the calling function without an error.

How about making it like this :

var anchor = document.createElement('a');

anchor.href = '#someDialog';
anchor.setAttribute('data-toggle','modal');
anchor.className='button';

anchor.onclick = function(){
  chnghost(pinfoarray);
}

您需要关闭字符串双引号以放置一个javascript变量:

var theHost = "<a href='#someDialog' onclick='chnghost('" + pinfoarray + "');' data-toggle='modal' class='button'>Change</a>";

You need to properly terminate the string and encode the parameter. You also need to guard against reserved characters in your data ( escapeHtml ).

var theHost = "<a href='#someDialog' onclick='chnghost(" + escapeHtml(JSON.stringify(pinfoarray)) + ");' data-toggle='modal' class='button'>Change</a>";

If you're using jQuery, you can implement escapeHtml like so:

function escapeHtml(text) {
    return $("<div/>").text(text).html();
}

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