简体   繁体   English

我在单引号的属性中得到双引号,我该如何阻止它?

[英]I'm getting double quotes inside the attributes of single quotes, How can I stop it?

I've a variable and I stored a tag in this.我有一个变量,我在其中存储了一个标签。 I set this tag inside the double quotes and my tag has some attributes and events which are in single quotes.我在双引号内设置了这个标签,我的标签有一些用单引号括起来的属性和事件。 Now problem is that I'm getting double quotes inside the tag which were single quotes before.现在的问题是我在标签内得到了双引号,而之前是单引号。 I want to get single quotes inside the tag of some attributes我想在某些属性的标签内获得单引号

var test= "<tr><td><input type='text' class='demo_class' onchange='myfun(this,'val')'></td></tr>"

It's giving me result in browser它在浏览器中给了我结果

<input type="text" class="demo_class" onchange="myfun(this,"val")">

but I want to get但我想得到

<input type="text" class="demo_class" onchange="myfun(this,'val')">
var test = '<tr><td><input type=\"text\" class=\"demo_class\" onchange=\"myfun(this,\'val\')\"></td></tr>';

You need to escape the quotes contain in a same quotes type with the \ symbole.您需要使用 \ 符号转义包含在相同引号类型中的引号。

Example:例子:

var test = '<tr><td><input type="text" class="demo_class" onchange="myfun(this,\'val\')"></td></tr>';

Else the string starting by ' or " is considered terminated to the first non escaped ' or " encountered.否则,以 ' 或 " 开头的字符串被认为终止于遇到的第一个非转义 ' 或 "。

Also the quotes delimiting the html's attributes values are always resolved to " independent of what you use ' or " in your js, so that can avoid most confusion to always delimite the values of your html attributes by the " symbole like in this example.此外,在您的 js 中,分隔 html 属性值的引号始终解析为“独立于您使用的内容”或“,这样可以避免大多数混淆,始终通过“符号”分隔 html 属性的值,如本例所示。

 document.body.innerHTML = '<input type="text" class="demo_class" onchange="myfun(this,\'val\')">';

You could try with two approaches:您可以尝试两种方法:

  1. Use a method to sanitize your HTML and send your test var through this: result = sanitize(test);使用一种方法来清理您的 HTML 并通过以下方式发送您的test变量: result = sanitize(test); . .

     const sanitize = (str) => { return String(str).replace(/"/g, "'"); };
  2. Try using HTML entities as &quot;尝试使用 HTML 实体作为&quot; and template literals instead of the simple quote symbol.模板文字而不是简单的引号符号。

const Q = "&quot;"
let test= `<tr><td><input type=${Q}text${Q} class=${Q}demo_class${Q} 
onchange=${Q}myfun(this,${Q}val${Q})${Q}></td></tr>`

EDIT编辑

  1. It's possible that it'll work with the string interpolation approach.它可能适用于字符串插值方法。
let test= `<tr><td><input type='text' class='demo_class' onchange='myfun(this, 'val')'></td></tr>`

I got the solution which is given below.我得到了下面给出的解决方案。

var test= "<tr><td><input type='text' class='demo_class' onchange='myfun(this,&apos;val&apos;)'></td></tr>"

Thank you all:)谢谢你们:)

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

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