简体   繁体   English

如何使jQuery / Javascript在PHP语句中工作?

[英]How to make jQuery/Javascript work in PHP statement?

I'm having some difficulties getting Javascript to execute in a PHP statement if it is possible at all. 如果有可能,让Javascript在PHP语句中执行会遇到一些困难。 Below I have the code, if the field 'First' is empty, then the background color of a certain div will be yellow. 在下面的代码中,如果'First'字段为空,则某个div的背景色将为黄色。 How can I get this to work properly if it is possible in the first place? 如果可以的话,如何使它正常工作? Thanks in advance. 提前致谢。

if (empty($_POST["First"])) {

    echo '<script type="text/javascript">';
    echo '$("div").css({"background-color":"yellow"});';
    echo '</script>';

} 

check this code. 检查此代码。 hope it will help you 希望对你有帮助

<div>Content Div</div>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<?php
 //$_POST["First"] = ''; if you want to check this code execute then remove comment then run this code
 if (empty($_POST["First"])) {
echo '<script type="text/javascript">';
echo '$("div").css("background-color","yellow");';
echo '</script>';
}
?>

you can also use this code 您也可以使用此代码

<div>Content Div</div>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<?php
//$_POST["First"] = ''; this is for test case if you want to check then remove comment then run this code
 if (empty($_POST["First"])) { ?>
<script type="text/javascript">
$("div").css("background-color","yellow");
</script>
<?php } ?>

in this code php tag and javascript tag use separate 在此代码中,php标签和javascript标签分别使用

You should try putting script tags inside php tags, like this: 您应该尝试将脚本标签放入php标签中,如下所示:

<?php 
    if (empty($_POST["First"])) { ?>
        <script type="text/javascript">
        '$("div").css({"background-color":"yellow"});';
        </script>
<?php } ?>

Here is an example: https://stackoverflow.com/a/13254287/7808973 这是一个示例: https : //stackoverflow.com/a/13254287/7808973

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

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