在JavaScript中需要第三种引号 [英] Need third kind of quotation marks in JavaScript

查看:125
本文介绍了在JavaScript中需要第三种引号的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在使用JavaScript更改HTML.因此,我有一个保存HTML代码的String,因为它是在for循环中生成的.其中有一个<a>标记.我想在<a>标记中添加onClick,该onClick调用带有保存在javascript变量中的参数的函数.

I'm changing the HTML using javascript. Therefore, I have a String that saves the HTML code, since it is produced in a for-loop. In it there is an <a> tag. To the <a> tag I want to add an onClick which calls a function with a parameter which is saved in a javascript variable.

let parameter = "p1";
let to_html_String = "<a href='#' onClick='create_sprite_window("+parameter+")'></a>";
document.getElementById('sidebar_left_sprites').innerHTML = to_html_String;

这不起作用,因为它将产生以下html:

This does not work because it would prodece the following html:

<a href='#' onClick='create_sprite_window(p1)'></a>

它不起作用,因为p1前后没有引号. 我的问题是我将需要第三种引号来解决此问题. 在下面的示例中,我将在需要引号的地方使用#:

It does not work because there are no quotation marks before and after p1. My problem is that I would need a third kind of quotation marks in order to solve this. In the following example I will use # where I would need those quotation marks:

let parameter = "p1";
let to_html_String = "<a href='#' onClick='create_sprite_window(#"+parameter+"#)'></a>";
document.getElementById('sidebar_left_sprites').innerHTML = to_html_String;

我不能使用单引号,因为它会终止onClick,而我不能使用双引号,因为它会终止于to_html_String.

I can't use a single quotation mark because it would end the onClick and I can't use double beacuse it would end to_html_String.

是否存在第三引号或解决此问题的另一种方法?

Are there third quotation marks or is there an other way to solve this?

推荐答案

如果您使用的是ES6,则可以使用

If you're using ES6, you can use template strings like

let foo = `Hello "World's"`;

无论如何-为什么您不只是逃脱引号呢?

Anyway - why wouldn't you just escape your quotation marks ?

let bar = 'hello \' world';
let buz = "hello \" world";

这篇关于在JavaScript中需要第三种引号的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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