我已经采取了一个网站,并有大量的JavaScript看起来像这样;
I have taken over a website and there is a lot of javascript that looks like this;
function BuildHTMLString(item) { return "<input name='Text' Type='text' value='" + item+ "' />"; }
这些字符串,然后被用于发布形式。我意识到,如果变量的项目中有一个撇号,这件事打破了。
these strings are then being used in posting forms. I realized that if the variable item has an apostrophe in it, this whole thing breaks down.
什么是推荐的方式来编程填充文本框,这将是一个表单提交,这并不在其中创建一个问题,用撇号名称的一部分。
What is a recommended way to programatically populate textboxes that will be part of a form post that doesn't create an issue with names with apostrophe in it.
推荐答案您可以使用的 document.createElement方法 以编程方式创建的元素,然后使用的 outerHTML 属性:
You could use document.createElement to create elements programmatically and then use the outerHTML property:
function buildHtmlString(item) { var element = document.createElement("input"); element.setAttribute("name", "Text"); element.setAttribute("type", "text"); element.setAttribute("value", item); return element.outerHTML; }在Chrome浏览器, buildHtmlString(这有一个引号\); 给我:
On Chrome, buildHtmlString("this has a quote \""); gives me:
<input name="Text" type="text" value="this has a quote "">
我注意到你加入了一个的jQuery 标记。所以,你可以很容易地做到这一点pretty的使用jQuery和:
I noticed that you added the jquery tag. So you can do this pretty easily with jQuery as well:
function buildHtmlString(item) { return jQuery("<input>").attr("name", "Text") .attr("type", "text") .attr("value", item) .get(0).outerHTML; }更多推荐
重构的javascript,以避免单引号引起的问题?
发布评论