我有包含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>
标记时开始加载外部脚本文件。文件一加载,浏览器就执行它,将click事件绑定到#user_button
。这发生在它处理您的<body>
标记之前,因此#user_button
还不是DOM的一部分。如果你试图检查
$('#user_button')
,你会发现它是空的。这个输出
我也遇到过类似的问题。当检查网络时,静态js正在从缓存加载。 当我关闭缓存时,它开始工作。 因此,您需要在开发期间重新启动调试服务器或关闭缓存。
相关问题 更多 >
编程相关推荐