Need third kind of quotation marks in JavaScript

和自甴很熟 提交于 2019-12-02 22:09:45

问题


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;

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

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

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;

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?


回答1:


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";



回答2:


Don’t build HTML using JavaScript. The DOM API will let you build document nodes cleanly and safely, and even attach event listeners so you don’t have to build JavaScript strings in the HTML you’re building in JavaScript.

let parameter = "p1";

const link = document.createElement('a');
link.href = '#';
link.textContent = 'maybe you want something in this link?';
link.addEventListener('click', function (e) {
    e.preventDefault();
    create_sprite_window(parameter);
});

document.getElementById('sidebar_left_sprites')
    .appendChild(link);
  • createElement
  • addEventListener
  • appendChild



回答3:


This will work

"<a href='#' onClick='create_sprite_window('"+parameter+"')></a>";



回答4:


/* Use \' to differentiate with function single quote */

let parameter = "p1"; let to_html_String = ""; document.getElementById('sidebar_left_sprites').innerHTML = to_html_String;



来源:https://stackoverflow.com/questions/38739465/need-third-kind-of-quotation-marks-in-javascript

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!