如果JS在php-if语句中,我在哪里声明JS依赖项

Where do i declare JS dependencies if the js is in a php if statement

本文关键字:JS 在哪里 声明 依赖 php-if 语句 如果      更新时间:2023-09-26

下面是一个弹出警报id的示例,我不确定我在哪里定义脚本的依赖项,是在head中吗?如果页面上没有html,我该怎么办?

if ($rowcount== 0)
{
echo ("<script>
    $(function(){
        $.jAlert({
            'title': 'nada',
            'content': 'nada',
            'closeOnEsc': false,
            'closeOnClick': false
        });
        $.jAlert({
            'title': 'click',
            'content': 'click',
            'closeOnClick': true
        });
        $.jAlert({
            'title': 'esc',
            'content': 'esc',
            'closeBtn': false,
            'closeOnEsc': true
        });
        errorAlert('test alert');
        successAlert('Hi!', 'You did it!');
        alert('test alert');
    });

 $connection->close();
 exit;
 }

我假设您谈论的是jQuery库。您必须在脚本之前声明您的依赖项(在本例中为jQuery库)。只要它总是在脚本之前,无论它是在文档末尾<body>标记之前还是在<head>标记中。否则,从技术上讲,脚本可以放在<body>标记中的任何位置,所以只需一起输出您现在所拥有的内容即可。

我会把你的代码改成这样:

if ($rowcount== 0)
{
?>
<script type="text/javascript" src="https://code.jquery.com/jquery-2.1.4.min.js"></script>
<script type="text/javascript" src="https://code.jquery.com/ui/1.11.4/jquery-ui.min.js"></script>
<script type="text/javascript" src="path/to/jquery-ui-jalert.js"></script>
<script>
    $(function(){
        $.jAlert({
            'title': 'nada',
            'content': 'nada',
            'closeOnEsc': false,
            'closeOnClick': false
        });
        $.jAlert({
            'title': 'click',
            'content': 'click',
            'closeOnClick': true
        });
        $.jAlert({
            'title': 'esc',
            'content': 'esc',
            'closeBtn': false,
            'closeOnEsc': true
        });
        errorAlert('test alert');
        successAlert('Hi!', 'You did it!');
        alert('test alert');
    });
</script>
<?php 
     $connection->close();
     exit;
}

===更新===

在本用例中,您看到的<?php?>本质上与echo相同。这样做:echo "Hi";?>Hi<?php 相同