重构的javascript,以避免单引号引起的问题? [英] Refactor javascript to avoid apostrophes causing issues?

查看:260
本文介绍了重构的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,以避免单引号引起的问题?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆