简体   繁体   English

Javascript转义双引号两次

[英]Javascript escape double quotes twice

I am having problems trying to display correctly the value of a text input field containing double quotes ("). 我在尝试正确显示包含双引号(“)的文本input字段的value时遇到问题。

Here is the code: 这是代码:

<script>
var locked;
function addHTML(html,id,replace){
    if(locked!=false){
        if(replace==true) document.getElementById(id).innerHTML = html;
        else document.getElementById(id).innerHTML = document.getElementById(id).innerHTML + html;
    }
}
</script>
<DIV id="divvalues">
    <div onclick='javascript:addHTML("<INPUT type=\"text\" id=\"inputvalues\" name=\"values\" value=\"Click on me, \"in double quotes\", click on me\" required size=53 />","divvalues",true); document.getElementById("inputvalues").focus();'>
        <span>Click on me, "in double quotes", click on me</span>
    </div>
</DIV>

As a result, only Click on me, is displayed in the input . 其结果是,只有点击了我,显示在input Any idea on how I should escape the double quotes inside the value attribute? 关于如何在value属性中转义双引号的任何想法吗?

It will probably be easier for you to debug if you create a function in your script instead of doing everything in your onclick. 如果您在脚本中创建一个函数而不是在onclick中执行所有操作,则调试起来可能会更容易。

Instead I would start by doing something like this: 相反,我将从做这样的事情开始:

<div onclick='yourFunction()'>

And in your Javascript: 在您的Javascript中:

function yourFunction()
{
    // code
}

\\“用双引号\\”在您的输入标签中添加了一个“标记。它们应该是”吗?

The best solution I have found is to move the HTML outside the onclick attribute and place it inside a Javascript var : 我发现最好的解决方案是将HTML移到onclick属性之外,然后将其放在Javascript var

<script>
var locked;
function addHTML(html,id,replace){
    if(locked!=false){
        if(replace==true) document.getElementById(id).innerHTML = html;
        else document.getElementById(id).innerHTML = document.getElementById(id).innerHTML + html;
    }
}

var divvalueshtml = '<INPUT type="text" id="inputvalues" name="values" value="Click on me, &quot;in double quotes&quot;, click on me" required size=53 />';
</script>
<DIV id="divvalues">
    <div onclick='javascript:addHTML(divvalueshtml,"divvalues",true); document.getElementById("inputvalues").focus();'>
        <span>Click on me, "in double quotes", click on me</span>
    </div>
</DIV>

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

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