简体   繁体   中英

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:

<?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

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

the code does not work anymore - test() function is not run, yet no error are produced.

Why?

UPD:

  1. test() function is in test.js
  2. code in test.js:

    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.

Complete html for the div:

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

This solved the problem and external .js is now apparently referenced correctly.

This is something very valuable I have learned!

The external .js file might not be loaded before the DOM is ready. 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. ( Reference )

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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