繁体   English   中英

HTML文本框值包括“”

[英]Html textbox value include “”

我在JavaScript中动态分配了一个文本框值:

var html = '';
for( var s=0;  s++ ; s<10){
  html += '<input type="hidden" name="hfstepDescription'+s+'" id="hfstepDescription'+s+'" value="'+ sstepDescriptionHTML +'">';

}

sstepDescriptionHTML的内容可能是这样

<input type="hidden" name="hfstepDescription11" id="hfstepDescription11" value="test1 <div class="">context1</div>">

但是当我使用document.getElementById('hfstepDescription11').value我会得到test1 <div class= ,而不是test1 <div class="">context1</div>

如何获得正确的值-> test1 <div class="">context1</div>

问题是编码。 如果您的值包含与该值括起来的相同字符,则基本上必须对其进行编码或以其他方式设置该值。

您可以选择两种不同的路径:

第一种选择是在将值插入到生成的HTML中之前对其进行转义:

var escapedValue = value.replace(/&/, "&amp;").replace(/\"/, "&quot;");

html += "<input type=\"hidden\" name=\"test\" id=\"test\" value=\"" + value + "\"/>";

另一种选择是在将HTML附加到DOM之后设置值:

document.getElementById("test").value = value;

我不确定在哪里设置sstepDescriptionHTML但是您确实需要对<input>的值进行HTML编码。 该值只会是双引号之间的值,因此为什么它只会返回: test1 <div class=

查看JavaScript的escape()函数

您必须将div中class属性的双引号替换为单引号。

<input type="hidden" name="hfstepDescription11" id="hfstepDescription11" value="test1 <div class=''>context1</div>" />

我使用escape()编码文本框的值,并使用下面的php代码解码文本框的值

那么我可以得到正确的值

$ str = uniDecode($ str,'big-5');

函数uniDecode($ str,$ charcode){$ text = preg_replace_callback(“ /%u [0-9A-Za-z] {4} /”,toUtf8,$ str); 返回mb_convert_encoding($ text,$ charcode,'utf-8'); }函数toUtf8($ ar){foreach($ ar as $ val){$ val = intval(substr($ val,2),16); if($ val <0x7F){// 0000-007F $ c。= chr($ val); } elseif($ val <0x800){// 0080-0800 $ c。= chr(0xC0 |($ val / 64)); $ c。= chr(0x80 |($ val%64)); } else {// 0800-FFFF $ c。= chr(0xE0 |(($ val / 64)/ 64)); $ c。= chr(0x80 |(($ val / 64)%64)); $ c。= chr(0x80 |($ val%64)); 返回$ c; }

我使用escape()编码文本框的值,并使用php代码-http: //www.neo.com.tw/archives/000152-解码文本框的值

那么我可以得到正确的值

您可以使用以下文章中描述的方法对其进行转义

http://hemanshubhojak.com/Home/Post?postId=7

暂无
暂无

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

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