jQuery 字符串内的jQuery变量,引号内的引号

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/11614599/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-26 10:46:38  来源:igfitidea点击:

jQuery variable within string, quotes within quotes

jquery

提问by Jonah Katz

I have the following jQuery code:

我有以下 jQuery 代码:

$(".container").append("<a href='javascript:void(0)'onClick='showField('"+data.name+"','"+data.text+"');'>Edit</a>");

Which is outputting (notice the quote problem before the 4and before the >edit:

这是输出(注意之前4和之前的报价问题>edit

<a href="javascript:void(0)" onclick="showField("4','school_type');'>Edit</a>

When it should be outputting:

什么时候应该输出:

<a href="javascript:void(0)" onclick="showField('4','school_type');">Edit</a>

回答by mgraph

try \"instead of 'in onClick:

尝试\"而不是'onClick

$(".container").append("<a href='javascript:void(0)' onClick=\"showField('"+data.name+"','"+data.text+"');\">Edit</a>");

回答by Josh Mein

You need to escape your "s with \

你需要逃避你的"s\

$(".container").append("<a href='javascript:void(0)' onClick='showField(\""+data.name+"\",\""+data.text+"\");'>Edit</a>");

Live DEMO

现场演示

回答by user28864

Although this reply is coming at a late hour, however you can also achieve what you want using something like this:

尽管此回复来得很晚,但是您也可以使用以下方法实现您想要的:

    var element = '<p class = ' + '"capitals"' + '> This is a new paragraph</p>'
    $(".container").append(element);

If you print the above code to debug console the following output will be printed:

如果将上述代码打印到调试控制台,将打印以下输出:

     <p class = "capitals">This is a new paragraph</p>

You can use double and single quotes combined togther like this '""'to print out double quotes. Another Example:

您可以像这样组合使用双引号和单引号'""'来打印双引号。另一个例子:

        var doublequotedtext = '"Hello"'; 
        debug.print(doublequotedtext);

so applying the above to your code:

因此将上述内容应用于您的代码:

       var element = '<a href = ' + '"javascript:void(0)"' + 'onClick = ' + '"showField(data.name,data.text);"' + '>Edit</a>'
       $(".container").append(element);