简体   繁体   English

在JavaScript中结合单引号和双引号

[英]Combining single and double quotes in JavaScript

I'm wondering if JavaScript has a writing format for using html elements that have both single and double quotes inside JavaScript functions. 我想知道JavaScript是否具有用于使用在JavaScript函数中同时具有单引号和双引号的html元素的书写格式。 May be something like heredoc for javascript or it could be a function in jQuery. 可能是类似于Heredoc的javascript,也可能是jQuery中的函数。 I couldn't find a solution to my problem and will try to describe it below: 我找不到解决问题的方法,将尝试在下面进行描述:

I am writing a web page on php. 我正在用php编写网页。 I have a page and there is a form in it. 我有一个页面,里面有一个form There is a jQuery function that appends select elements to a form. 有一个jQuery函数将select元素附加到表单。 After appending, user selects some options and submit the form. 追加后,用户选择一些选项并提交表单。 (I really wanted to paste a whole code here to make it clearer, but there is a big amount of code which is not so nice, so I tried to simplify it for you, sorry for some bad code) (我真的很想在此处粘贴整个代码以使其更清晰,但是有很多代码不是那么好,所以我尝试为您简化代码,对不起一些不好的代码)

I have a php variable like this one ( select has onchange event, showUser is a function with AJAX request): 我有一个像这样的php变量( select具有onchange事件, showUser是具有AJAX请求的函数):

$string = <<<EOT
<select name="sapak[]" onchange='showUser(this.value, document.getElementsByName("dereje[]")[0].value)'>
EOT;

And there are many option in between and of course closing </select> (I didn't write all the code to be shorter). 而且之间还有很多option ,当然还有</select> (我没有写出所有较短的代码)。 A part of jQuery function that appends select to the form : jQuery函数的一部分,将select附加到form

$(wrapper).append('<div> <? echo $string; ?> <a href="#" class="remove_field">Del</a></div>');

My problem here is that in $string variable I have to use single and double quotes, and when it comes to append() function in jQuery I use quotes again. 我的问题是在$string变量中,我必须使用单引号和双引号,当涉及到jQuery中的append()函数时,我再次使用引号。 And all these give me error in browser's console Uncaught SyntaxError: Unexpected identifier , because of single quotes started at append(' , but ending at onchange=' . Is there are any smart solution for this? I thought that heredoc will be, I've googled and I think that actually there is no heredoc for javascript. May be some other formattings available? 所有这些给我带来了浏览器控制台错误Uncaught SyntaxError: Unexpected identifier ,因为单引号始于append(' ,但以onchange='结尾。是否有任何明智的解决方案?我以为Heredoc会是,我ve google,我认为实际上没有javascript的Heredoc。可能还有其他格式可用吗?

This should work : 这应该工作:

$(wrapper).append("<div> <? echo $string; ?> </div>");

$string = <<<EOT
<select name=\"sapak[]\" onchange=\"showUser(this.value, document.getElementsByName('dereje[]')[0].value)\">
EOT;

As @Imperative advises about character escaping 正如@Imperative建议有关字符转义

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

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