简体   繁体   English

用PHP生成的Javascript字符串中的转义引号字符

[英]Escape quote character within string in Javascript generated with PHP

Not sure if that title makes any sense but I'll try and explain it. 不知道该标题是否有意义,但我会尽力解释。

I am generating some content with PHP. 我正在用PHP生成一些内容。

What I am attemtping to generate is a string that will spit out an URL with some JavaScript in the onlick event if the user has JavaScript enabled, and then a regular link if the JavaScript is not enabled. 我要生成的是一个字符串,如果用户启用了JavaScript,则会在onlick事件中吐出带有一些JavaScript的URL,然后如果未启用JavaScript,则生成一个常规链接。

$url = "<script type=\"text/javascript\">
    document.write(\"<a href='#' onclick='$('#UserID').val(" . 
            mysql_result($recordset, $count, "userid") . "); return false;'>
        Click here
    </a>\");
</script>
<noscript>
    <a href=\"/scripts/updateuser.php?id=" . 
            mysql_result($recordset, $count, "userid") . "\">Click here</a>
</noscript>"; 

The problem I am running into is the jQuery selector for #UserID. 我遇到的问题是#UserID的jQuery选择器。 Since it's single quoted it bombs out there when clicked and processes the hash mark and goes to the top of the page ignoring the return false. 因为它是单引号,所以在单击时会炸开,并处理井号,然后转到页面顶部,忽略return false。

I can't put double quotes there because that's at the start and end of my document.write statement. 我不能在其中加上双引号,因为那是在document.write语句的开头和结尾。

Any ideas on how to structure the string around the jQuery selector here using escape characters or whatever? 关于如何使用转义字符或其他内容围绕jQuery选择器构造字符串的任何想法?

You can use $(\\\\'#UserID\\\\') . 您可以使用$(\\\\'#UserID\\\\') The double backslash is to make PHP put one extra backslash, making them usable in the onclick attribute. 双反斜杠是使PHP加上一个额外的反斜杠,以使其在onclick属性中可用。 (Besides that, the first comment on the question should be followed rather than using this answer.) (此外,应遵循对该问题的第一条评论,而不要使用此答案。)

Good god that's ugly. 好丑的上帝。 Try this on for size: 尝试以下尺寸:

$userid = mysql_result($recordset, $count, "userid");

$url = <<<EOL
<script type="text/javascript">
    document.write('<a href="#" onclick="$(\'#UserID\').val({$userid})); return false;">Click here</a>');
/script>
<noscript><a href="scripts/updateuser.php?id={$userID}">Click here</a></noscript>
EOL;

I won't get into how 1990's document.write is, but how about this: 我不会研究1990年代的document.write的情况,但是如何处理:

<?php
    $userid = ...
?>
<a href="scripts/updateuser.php?id=<?php echo $userid ?>" onclick="$('#UserID').val({$userid}); return false;">Click here</a>

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

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