当它在外部文件中时,Flask应用程序不执行javascript

Flask app not executing javascript when it's in an external file

本文关键字:应用程序 Flask 执行 javascript 外部 文件      更新时间:2023-09-26

我有包含我的CSS和JS的HTML文件。当创建我的flask应用程序时,我决定将CSS和JS分开,在一个静态目录中单独存放文件。

当我把所有的东西都放在一个HTML文件中时,一切都按预期工作,但是当CSS和JS在不同的文件中时,JS的部分不会执行。

这是我在HTML文件中的导入:

<head>
    <script src="http://ajax.googleapis.com/ajax/libs/jquery/1.11.0/jquery.min.js"></script>
    <script type="text/javascript" src="{{ url_for('static', filename='scripts/main.js') }}"></script>
    <link rel="stylesheet" href="http://yui.yahooapis.com/pure/0.4.2/pure-min.css">
    <link rel="stylesheet" href="{{ url_for('static', filename='css/main.css') }}">
</head>
这是独立JS文件的内容:
$('#user_button').click(function(event) {
    $("#user_id").html($('option:selected').html());
    $('.button_div').show();
});
var prodData = [];
var boughtProds = [];
$('.prod_button').click(function(event) {
    if (boughtProds.indexOf($(this).data('name')) == -1) {
        prodData.push({
            name: $(this).data('name'),
            price: $(this).data('price'),
            quantity: 1,
        });
        boughtProds.push($(this).data('name'));
    } else {
        prodData[boughtProds.indexOf($(this).data('name'))].quantity = prodData[boughtProds.indexOf($(this).data('name'))].quantity + 1;
    }
    var total = 0;
    for (var x in prodData) total += prodData[x].price * prodData[x].quantity
    total = Math.round(total * 100) / 100
    var subtotal = '<tr><td></td><td>Subtotal</td><td>$' + total + '</td></tr>';
    var allProds = '';
    $.each(prodData, function(k, v) {
        allProds = allProds + '<tr><td>' + v.name + '</td><td>' + v.quantity + 'x</td><td>@ $' + v.price + ' each</td></tr>'n';
    });
    $('.table_contents > tbody').html(allProds);
    $('.table_contents > tfoot').html(subtotal);
});
$(document).ready(
    function() {
        $('.button_div').hide();
    })

奇怪的是,这个函数在文档加载时正常工作:

 $(document).ready(
        function() {
            $('.button_div').hide();
        })

和这个函数不工作:

$('#user_button').click(function(event) {
    $("#user_id").html($('option:selected').html());
    $('.button_div').show();
});

但更奇怪的是,当所有内容都在一个HTML文件中时,所有内容都可以正常工作。

任何想法吗?

您要么需要将<script type="text/javascript" src="{{ url_for('static', filename='scripts/main.js') }}"></script>移到<head>标签之外(例如,移到<body>的末尾),要么需要将$('#user_button').click(...);放在$(document).ready(...);中。

发生的事情是,你的浏览器开始加载你的外部脚本文件,因为它处理你的<head>标签。一旦加载文件,浏览器就执行它,将单击事件绑定到#user_button。这发生在它处理<body>标记之前,因此#user_button还不是DOM的一部分。

如果你试图检查$('#user_button'),你会看到它是空的。

console.log($('#user_button'));
这个输出

[]

我也遇到过类似的问题。当检查网络时,静态js正在从缓存加载。当我关闭缓存时,它开始工作了。因此,您需要在开发期间重新启动调试服务器或关闭缓存。