简体   繁体   English

将数组传递给函数并在Javascript中转义双引号

[英]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. 我正在生成动态HTML,并希望将数组传递给调用函数。 The array is also being dynamically generated. 该数组也正在动态生成。

The contents of pinfoarray are somewhat like this "Ice Hockey","Junior Basketball","Ladies Soccer" pinfoarray的内容有点像“冰球”,“少年篮球”,“女子足球”

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 ). 您还需要防止数据中的保留字符( 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: 如果您使用的是jQuery,则可以这样实现escapeHtml:

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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