简体   繁体   English

为什么我的PHP生成的javascript无法正常工作?

[英]Why doesn't my PHP-generated javascript work?

i have the following javascript code 我有以下javascript代码

echo ' <a href = "javascript:void(0)" onclick = "document.getElementById("items").style.display="block";document.getElementById("fade").style.display="block""><span style="padding-left:0px"><input type="submit" name="r" style="width: 138px; font-weight:bold;  " value="Add item"/></span></a>
';

i am trying to execute the script from within a php script. 我试图从php脚本中执行脚本。 when i click on the button to execute the java part of it, nothing happens. 当我单击按钮执行它的Java部分时,什么也没发生。 i then try it this way 然后我这样尝试

echo ' <a href = "javascript:void(0)" onclick = "document.getElementById('items').style.display='block';document.getElementById('fade').style.display='block'"><span style="padding-left:0px"><input type="submit" name="r" style="width: 138px; font-weight:bold;  " value="Add item"/></span></a>
';

and got this parse error: parse error, expecting '," or ';". 并得到以下解析错误:解析错误,期望为'," or “;”。

You have to escape apostrophes in a string in php. 您必须在php字符串中转义撇号。 Instead of 代替

echo '(...) style.display='block' (...)';

do

echo '(...) style.display=\'block\' (...)';

That being said, try to split your code over multiple lines so it is at least somewhat readable. 话虽这么说,请尝试将您的代码分成多行,以便至少在某种程度上可读。 You can also write HTML in php like this: 您也可以像这样在php中编写HTML:

<?php
// php code
echo 'php';
?>
<HTML code>
<?php
// more php code
echo ' <a href = "javascript:void(0)" onclick = "document.getElementById('items').style.display='block';document.getElementById('fade').style.display='block'"><span style="padding-left:0px"><input type="submit" name="r" style="width: 138px; font-weight:bold;  " value="Add item"/></span></a>
';

This will not work because the single quote params in the JS echo are breaking the PHP flow. 这将不起作用,因为JS回声中的单引号参数破坏了PHP流程。 Try adding break characters before each single quotation in the echo, not sure what it is in PHP but try \\' 尝试在回显中的每个单引号之前添加分隔符,但不确定在PHP中是什么,但尝试\\'

IE: IE浏览器:

Id('items')

becomes 变成

Id(\'items\')

This has nothing to do with PHP. 这与PHP无关。

You are using " quotes to delimit JavaScript strings inside an HTML attribute values delimited using " characters. 您正在使用"引号来分隔的HTML属性值的JavaScript字符串使用分隔"字符。

As a result, the first " inside the JS terminates the HTML attribute value. 结果,JS内部的第一个"终止了HTML属性值。

The quick hack is to use &quot; 快速的技巧是使用&quot; instead of " inside the attribute value. 而不是在属性值内添加"

The better solution is to use unobtrusive JavaScript 更好的解决方案是使用兼容的JavaScript

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

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