重构的javascript,以避免单引号引起的问题?

编程入门 行业动态 更新时间:2024-10-21 12:39:10
本文介绍了重构的javascript,以避免单引号引起的问题?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧! 问题描述

我已经采取了一个网站,并有大量的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 &quot;">

我注意到你加入了一个的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,以避免单引号引起的问题?

本文发布于:2023-11-10 22:11:50,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1576600.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:重构   单引号   以避免   javascript

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!