从 PHP 调用 jQuery 函数
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/6722747/
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
Call jQuery function from PHP
提问by Daniel
How do I call a jQuery function from PHP?
如何从 PHP 调用 jQuery 函数?
<?php
if ($error == 1) {
?>
<script type="text/javascript">
error('1');
</script>
<?
}
?>
It doesn′t work.
它不起作用。
回答by Eric Herlitz
No you cannot call jQuery functions from PHP. But you can generate html with PHP that will execute jQuery functions at runtime.
不,您不能从 PHP 调用 jQuery 函数。但是您可以使用 PHP 生成 html,该 html 将在运行时执行 jQuery 函数。
- Javascript is sent to the client and executed there
- PHP is compiled at the server and then sent to the client
- Javascript 被发送到客户端并在那里执行
- PHP在服务器端编译,然后发送到客户端
Big difference in that
大不同
回答by Kun Ban
The script tags cannot be injected directly into php tags.... But if you echo it, the script will work.... The following code works :
脚本标签不能直接注入到 php 标签中......但是如果你回显它,脚本就会工作......下面的代码有效:
<?php
if( some condition ){
echo "<script>alert('Hello World');</script>";
}
?>
In case of using jQuery, you have to wrap the code in:
在使用 jQuery 的情况下,您必须将代码包装在:
jQuery(function(){
//Your Code
});
and then echo it....
然后回声它....
回答by user834929
It depends on where you place this code fragment within the HTML output.
这取决于您将此代码片段放置在 HTML 输出中的位置。
One of these solutions, I think, should work:
我认为这些解决方案之一应该有效:
<?php
if ($error == 1) {
?>
<script type="text/javascript">
$(function() {
error('1');
})
</script>
<?
}
?>
<?php
if ($error == 1) {
?>
<script type="text/javascript">
$(document).ready(
function() {
error('1');
}
)
</script>
<?
}
?>
回答by Cin Sb Sangpi
<?php
if(this == that) {
//do something in php
} else {
//do something with jquery (i.e. fade something in/out
}
?>
?>
回答by Gus
You need to specify that error('1')
is a call to a jQuery function:
您需要指定这error('1')
是对 jQuery 函数的调用:
jQuery.error('1');
// or, uning the $ alias:
$.error('1');