Click事件仅在外部JS文件中使用时不起作用

时间:2015-06-10 23:05:50

标签: javascript jquery click

在外部main.js中使用时(见下面的内容),只有“就绪!!”文字显示出来。但是当内联使用时没有引用main.js(见下文)两个“就绪!!”并“点击!!”文本显示。知道为什么我会错过这里吗?

页面内容案例1

Constructing B
Printing from B with size : 4
Constructing B
Constructing D
Printing from D with size : 8
Printing from D with size : 8

页面内容案例2

<!DOCTYPE html>
<html lang="en">    
<head>
    <meta charset="UTF-8">
    <title>Test</title>    
    <script type='text/javascript' src='http://mywpblog.com/wp-includes/js/jquery/jquery.js?ver=1.11.2'></script>    
</head>    
<body>
    <button class="purchase-test" type="button"></button>    
    <script type='text/javascript' src='http://mywpblog.com/wp-content/plugins/mytestplugin/assets/js/main.js?ver=3.0.1'></script>
</body>    
</html>

main.js

<!DOCTYPE html>
<html lang="en">    
<head>
    <meta charset="UTF-8">
    <title>Test</title>
    <script type='text/javascript' src='http://mywpblog.com/wp-includes/js/jquery/jquery.js?ver=1.11.2'></script>
</head>    
<body>
    <button class="purchase-test" type="button"></button>
    <script>
        JQuery(document).ready(function() {
            console.log("ready!!"); // WOKRS FINE
            JQuery('.purchase-test').click(function(e) {
                console.log("clicked!!"); // WOKRS FINE AS WELL
            });
        });
    </script>
</body>
</html>

1 个答案:

答案 0 :(得分:0)

$(function() {
    $('.purchase-test').on("click", function(event) {
        // If '.purchase-test' is a link: 
        // <a href="" class="purchase-test">A Link</a>
        // You must preventDefault
        event.preventDefault()

        // Log to console
        console.log("Clicking Purchase test");
    });
    $('.non-purchase-test').on("click", function(event) {
       console.log("Clicking Non Purchase Test");
    });
    $(".purchase-test-button").on("click", function(event) {
       console.log("Clicking on Button"); 
    });
});

https://jsfiddle.net/cpcmn41z/1/