简体   繁体   English

在.php页面上使用外部.js文件

[英]Using external .js files on a .php page

This code in index.php works and test(), which is defined in test.js produces the desired alert in the browser: index.php中的以下代码可以工作,并且在test.js中定义的test()可以在浏览器中生成所需的警报:

<?php 
    #include ('db.php');
    #$dataBase = new PDO("mysql:host=$dbHost;dbname=$dbName", $dbUser, $dbPass);    
    #PREPARE AND TRY    
    #$statement = $dataBase->query('SELECT * FROM users');
    #$rowCount = $statement->rowCount();
    #echo 'There are currently ' . $rowCount . ' rows in the database'; 
?>
<HTML>
    <HEAD>
        <meta charset="utf-8">
        <TITLE>title</TITLE>
        <script type="text/javascript" src="jquery-2.1.1.min.js"></script>
        <script type="text/javascript" src="ui/jquery-ui/jquery-ui.min.js"></script>
        <script type="text/javascript" src="test.js"></script>
        <link rel="stylesheet" type="text/css" href="test.css" />
        <link rel="stylesheet" href="ui/jquery-ui/jquery-ui.min.css" /> 
        <link rel="stylesheet" href="styles/jquery-ui-config.css" />        
    </HEAD>
    <BODY>

        <div id = 'clickablebutton'>Button</div>

        <script>
        $(document).ready(function(){
            //console.log('self invoke on document ready');
            $('#clickablebutton').click(function(){
                test();  //alerts "it works"
            });
        </script>
    </BODY>
</HTML>

However, when I remove whatever is in <script> tag and add the onclick attribute to <div> to look like 但是,当我删除<script>标记中的所有内容并将onclick属性添加到<div> ,如下所示:

<div id = 'clickablebutton' onclick='test()'>Button</div>

the code does not work anymore - test() function is not run, yet no error are produced. 该代码不再起作用-未运行test()函数,但未产生任何错误。

Why? 为什么?

UPD: UPD:

  1. test() function is in test.js test()函数在test.js中
  2. code in test.js: test.js中的代码:

    var test = function(){ alert('Works!'); var test = function(){alert('Works!');
    }; };

There was a post in the thread, which for some reason got deleted. 该线程中有一个帖子,由于某种原因被删除。 The suggestion was to explicitly state javascript:test() in the HTML. 建议在HTML中明确声明javascript:test()

Complete html for the div: 完成div的html:

<div id = 'clickablebutton' onclick='javascript:test()'>Button</div>

This solved the problem and external .js is now apparently referenced correctly. 这解决了问题,并且现在显然已正确引用了外部.js。

This is something very valuable I have learned! 这是我学到的非常有价值的东西!

The external .js file might not be loaded before the DOM is ready. 在DOM准备就绪之前,可能不会加载外部.js文件。 So it can't find the test function 所以找不到测试功能

You should either use jquery ready call, or use jQuery.holdReady() if you can't use jquery ready for some reason. 您应该使用jquery ready调用,或者如果由于某种原因无法使用jquery ready,请使用jQuery.holdReady()。 ( Reference ) 参考

$.holdReady( true );
$.getScript( "test.js", function() {
  $.holdReady( false );
});

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

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