javascript(jquery)函数中的转义特殊字符

escape special characters in javascript (jquery) function

本文关键字:转义 特殊字符 函数 jquery javascript      更新时间:2023-09-26

我有一行在jquery中附加了这个:

$('#league2').append("<input type='"button'" id='"2btn'" value='"1.2'" class='"butta'"  onmousedown='"active('exam''ple','awayteam')");

注意"考试文件"。。。我逃离了"与''"因此,当单击按钮时,激活的功能应该会起作用。

这是激活的功能:

function active(hometeam,awayteam){
alert("if this is alerted, it works!");
}

当我点击按钮时,它应该提醒"如果这被提醒了,它就工作了!",但它没有提醒它。它认为,因为当我使用该功能时,这是输出:

function active(exam''ple,awayteam){

当我在同一个东西后面加上一个不包含"'"的单词时,它就起作用了。

您需要为活动函数转义参数中的反斜杠,而不是撇号。

$('#league2').append("<input type='"button'" id='"2btn'" value='"1.2'" class='"butta'"  onmousedown='"active('exam'''ple','awayteam')");

要用php转义字符串并将其附加到代码中,可以使用正则表达式。以下内容适用于您的情况。

// Replaces a backslash with four backslashes: The 'append' function will interpret it as two backslashes; the 'active' function, as only one.
$str = preg_replace("/''''/", "''''''''''''''''", $str);
// Replaces an apostrophe with two backslashes and an apostrophe, then javascript will append only one backslash and an apostrophe, escaping that way an apostrophe.
$str = preg_replace("/'/", "'''''''''", $str);
// Replaces quotations with a backslash and quotations: the quotations will be escaped inside the append function, so one quotations will be printed out on your HTML
$str = preg_replace("/'"/", "'''''"", $str);

如果你不知道正则表达式(regex)是什么,我建议你研究一下如何使用它们。他们会帮你很多。

编辑:由于某种原因,最后一个程序需要两个反斜杠才能工作。已更新。

当字符串为双引号时,不需要转义单引号。最好的做法是将整个字符串用单引号括起来,这样就可以使用双引号而无需转义。(或者用双引号括起来的单引号)。

例如:

$("#thing").append('<div id="foo" class="bar" style="color:black;" onclick="foobar()"></div>');

您的代码有点复杂,因为有多个级别(您考虑过jQuery的点击吗?):

$('#league2').append('<input type="button" id="2btn" value="1.2" class="butta"  onmousedown="active('exam''ple','awayteam')');